@microsoft/copilot-sdk 1.0.29-unstable.42916223485.gfff36db → 2.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +596 -427
  2. package/dist/canvas.d.ts +4 -0
  3. package/dist/canvas.js +1 -0
  4. package/dist/cjs/canvas.js +1 -0
  5. package/dist/cjs/cliVersion.js +1 -1
  6. package/dist/cjs/client.js +1076 -634
  7. package/dist/cjs/copilotRequestHandler.js +24 -1
  8. package/dist/cjs/extension.js +15 -10
  9. package/dist/cjs/generated/rpc.js +302 -23
  10. package/dist/cjs/index.js +12 -2
  11. package/dist/cjs/localModelJson.js +103 -0
  12. package/dist/cjs/providerConfiguration.js +39 -0
  13. package/dist/cjs/rpcCancellation.js +49 -0
  14. package/dist/cjs/sdkProtocolVersion.js +1 -1
  15. package/dist/cjs/session.js +157 -12
  16. package/dist/cjs/taskAnalyticsJson.js +47 -0
  17. package/dist/cjs/toolSet.js +1 -1
  18. package/dist/cjs/types.js +54 -15
  19. package/dist/cjs/workflow.js +145 -1
  20. package/dist/cliVersion.d.ts +1 -1
  21. package/dist/cliVersion.js +1 -1
  22. package/dist/client.d.ts +68 -48
  23. package/dist/client.js +1087 -637
  24. package/dist/copilotRequestHandler.js +24 -1
  25. package/dist/extension.d.ts +18 -6
  26. package/dist/extension.js +15 -10
  27. package/dist/generated/lifecycle-diagnostics.d.ts +48 -40
  28. package/dist/generated/rpc.d.ts +4532 -967
  29. package/dist/generated/rpc.js +302 -23
  30. package/dist/generated/session-events.d.ts +374 -115
  31. package/dist/host.d.ts +7 -3
  32. package/dist/index.d.ts +10 -5
  33. package/dist/index.js +14 -2
  34. package/dist/localModelJson.d.ts +1 -0
  35. package/dist/localModelJson.js +69 -0
  36. package/dist/providerConfiguration.d.ts +3 -0
  37. package/dist/providerConfiguration.js +15 -0
  38. package/dist/rpcCancellation.d.ts +3 -0
  39. package/dist/rpcCancellation.js +25 -0
  40. package/dist/sdkProtocolVersion.d.ts +1 -1
  41. package/dist/sdkProtocolVersion.js +1 -1
  42. package/dist/session.d.ts +69 -10
  43. package/dist/session.js +158 -12
  44. package/dist/taskAnalyticsJson.d.ts +8 -0
  45. package/dist/taskAnalyticsJson.js +12 -0
  46. package/dist/toolSet.d.ts +6 -5
  47. package/dist/toolSet.js +1 -1
  48. package/dist/types.d.ts +1435 -1296
  49. package/dist/types.js +53 -15
  50. package/dist/workflow.d.ts +60 -14
  51. package/dist/workflow.js +143 -1
  52. package/docs/agent-author.md +11 -11
  53. package/docs/examples.md +1 -1
  54. package/docs/extensions.md +41 -2
  55. package/docs/workflows.md +52 -17
  56. package/package.json +16 -15
package/README.md CHANGED
@@ -22,7 +22,7 @@ replaces both with the CLI version published for that snapshot.
22
22
  `COPILOT_CLI_DOWNLOAD_BASE_URL` to use a release mirror while packaging.
23
23
  Standalone source builds acquire stable/prerelease runtime assets from
24
24
  `github/copilot-cli` at `v<runtime-version>`, and canonical unstable assets from
25
- `github/copilot-sdk` at `runtime-<runtime-version>`. Both checksum and package
25
+ `microsoft/copilot-sdk` at `runtime-<runtime-version>`. Both checksum and package
26
26
  downloads use that release location; mirror overrides retain the same tag scheme.
27
27
  Release workflows instead set `COPILOT_SDK_RUNTIME_PACKAGE_DIR` to a directory
28
28
  containing validated runtime npm package roots named for all eight platforms.
@@ -44,8 +44,8 @@ npm install @microsoft/copilot-sdk
44
44
  ## Model provider metadata
45
45
 
46
46
  `client.listModels()` and `client.rpc.models.list()` preserve the runtime's optional
47
- `provider` reference on each model: `{ id, kind, label }`. The existing `Model`,
48
- `ModelInfo`, and `ModelProviderRef` types are available from the package root.
47
+ `provider` reference on each model: `{ id, kind, label }`. The existing `Model`
48
+ and `ModelProviderRef` types are available from the package root.
49
49
  Native kinds remain `copilot` and `loki`; `id` is opaque and `label` is display text.
50
50
  Configured BYOK and older, unattributed rows omit `provider`; do not infer Copilot
51
51
  branding from a model ID or fill it from the active account. This metadata identifies
@@ -53,21 +53,25 @@ the model source, not the agent harness, an account, or a new routing/selection
53
53
 
54
54
  ## Network callbacks (experimental)
55
55
 
56
- Provide `network` in `CopilotClientOptions` when the SDK host should take over parts of the runtime's networking, for example when the runtime runs in WSL or a container and should use VS Code's proxy settings and the host's Kerberos tickets. Registration happens during `start()`, before sessions can be created. Without this option, or for a callback you leave out, the runtime handles that part itself.
56
+ Provide `network` in `CopilotClientOptions` when the SDK host should take over parts of the runtime's networking, for example when the runtime runs in WSL or a container and should use VS Code's proxy settings, proxy credentials and the host's Kerberos tickets. Registration happens during `start()`, before sessions can be created. Without this option, or for a callback you leave out, the runtime handles that part itself.
57
57
 
58
58
  - `resolveProxy({ url }, signal)` decides the proxies for every request the runtime would otherwise route by ambient proxy settings: proxy environment variables, `NO_PROXY` and operating-system proxy settings are not consulted unless it returns `undefined`. `url` is the request target as a PAC script sees it: without credentials or fragment, and for `https` and `wss` also without path and query. Return a PAC-style list such as `PROXY proxy.example:8080; HTTPS proxy.example:443; DIRECT` (the format of Electron's `session.resolveProxy`); return `DIRECT` for a direct connection, or `undefined` to let the runtime resolve the proxy itself, as if no callback were registered. Entry types the runtime doesn't support, such as SOCKS and QUIC, are skipped. If the callback fails, the request fails rather than connecting directly. Requests to loopback targets, and requests with an explicitly configured proxy, never consult it. The runtime caches answers, including `undefined`, for 5 seconds and waits at most 10 seconds for the callback.
59
- - `authenticateNegotiate({ spn }, signal)` supplies the Kerberos token for a proxy's Negotiate challenge instead of the runtime's native credential lookup. `spn` is a service principal in the platform-independent `service/host[@REALM]` form; validate it before issuing credentials. Return a fresh base64 SPNEGO token without the `Negotiate ` prefix, or `undefined` when credentials are unavailable, which fails the request. The runtime waits at most 30 seconds for the callback (less when the request's own deadline is sooner). Tokens are not cached and must not be logged or persisted. The callback supplies the initial SPNEGO token only; exchanges requiring continuation tokens are not supported. Proxies chosen by `resolveProxy` are authenticated the same way.
59
+ - `authenticateNegotiate({ spn }, signal)` supplies the Kerberos token for a proxy's Negotiate challenge instead of the runtime's native credential lookup. `spn` is a service principal in the platform-independent `service/host[@REALM]` form; validate it before issuing credentials. Return a fresh base64 SPNEGO token without the `Negotiate ` prefix, or `undefined` when credentials are unavailable, which fails the request unless the proxy also offers Basic and `authenticateBasic` supplies credentials. The runtime waits at most 30 seconds for the callback (less when the request's own deadline is sooner). Tokens are not cached and must not be logged or persisted. The callback supplies the initial SPNEGO token only; exchanges requiring continuation tokens are not supported. Proxies chosen by `resolveProxy` are authenticated the same way.
60
+ - `authenticateBasic({ proxy, realm, previousRejected }, signal)` supplies the credentials for a proxy's Basic challenge on requests the runtime tunnels through the proxy (`https` and `wss`). `proxy` is the proxy as `http://host:port` or `https://host:port`; `realm` comes from the proxy, so treat it as untrusted text. Return `{ username, password }`, or `undefined` when credentials are unavailable, which fails the request with the proxy's challenge; an empty user name counts as unavailable, the user name must not contain a colon, neither the user name nor the password may contain control characters, and an omitted password means an empty one. The runtime remembers the answer for that proxy and uses it for later connections, until the proxy rejects it; then it calls again with `previousRejected` set, so return different credentials, for example by asking the user, or `undefined`. A later connection sends the answer without waiting for a challenge, unless the runtime may try Negotiate with that proxy first. A connection submits at most three sets of credentials. While a call is pending, other requests through that proxy wait for its answer. When a proxy offers both Negotiate and Basic, the runtime prefers Negotiate and answers with Basic when Negotiate is unavailable or the proxy rejects it. The runtime does not time the callback out: a request whose own deadline passes stops waiting, but the answer is still remembered. Credentials must not be logged or persisted.
60
61
 
61
62
  Each callback's `signal` aborts when the runtime stops waiting (it cancels the request, for example after its timeout, or the connection closes); the SDK then stops awaiting the callback and ignores any later result.
62
63
 
63
64
  By default the callbacks serve only requests made for sessions this client creates or resumes. With `scope: "runtime"` they also serve the runtime's shared traffic, such as catalog refreshes, telemetry and remote MCP server connections; only one connection at a time can hold that scope, so startup fails if another client holds it. The registration ends when the connection closes.
64
65
 
65
66
  ```ts
66
- const client = new CopilotClient({ mode: "coding-agent",
67
+ const client = new CopilotClient({
68
+ mode: "coding-agent",
67
69
  network: {
68
70
  scope: "runtime",
69
71
  resolveProxy: async ({ url }) => session.resolveProxy(url),
70
72
  authenticateNegotiate: async ({ spn }, signal) => acquireToken(spn, signal),
73
+ authenticateBasic: async ({ proxy, realm }, signal) =>
74
+ promptForCredentials(proxy, realm, signal),
71
75
  },
72
76
  });
73
77
  ```
@@ -78,6 +82,7 @@ const client = new CopilotClient({ mode: "coding-agent",
78
82
  (`requireIdentity` and a validator returning `{identity,expiresAt}` or `null`):
79
83
 
80
84
  <!-- docs-validate: strict -->
85
+
81
86
  ```typescript
82
87
  import { CopilotClient } from "@microsoft/copilot-sdk";
83
88
 
@@ -150,6 +155,7 @@ by the SDK. Published sessions remain discoverable after hosting stops.
150
155
  Supply `createSession` to materialize fresh AHP sessions in your application:
151
156
 
152
157
  <!-- docs-validate: strict -->
158
+
153
159
  ```typescript
154
160
  import { approveAll, CopilotClient, defineTool } from "@microsoft/copilot-sdk";
155
161
 
@@ -161,15 +167,21 @@ await using host = await client.startAhpHost({
161
167
  signal.throwIfAborted();
162
168
  return client.createSession({
163
169
  ...config,
164
- onPermissionRequest: approveAll,
170
+ permissions: {
171
+ ...config.permissions,
172
+ onRequest: approveAll,
173
+ },
165
174
  systemMessage: { mode: "append", content: "Use the app's greeting tool." },
166
- tools: [
167
- defineTool("greeting", {
168
- description: "Get the application's greeting",
169
- parameters: { type: "object", properties: {} },
170
- handler: () => "Hello from the application!",
171
- }),
172
- ],
175
+ tools: {
176
+ ...config.tools?.definitions,
177
+ definitions: [
178
+ defineTool("greeting", {
179
+ description: "Get the application's greeting",
180
+ parameters: { type: "object", properties: {} },
181
+ handler: () => "Hello from the application!",
182
+ }),
183
+ ],
184
+ },
173
185
  });
174
186
  },
175
187
  onSessionReleased: async (originalSession) => {
@@ -247,7 +259,9 @@ await client.start();
247
259
  // approveAll is only valid when managed settings are disabled.
248
260
  const session = await client.createSession({
249
261
  model: "gpt-5",
250
- onPermissionRequest: approveAll,
262
+ permissions: {
263
+ onRequest: approveAll,
264
+ },
251
265
  });
252
266
 
253
267
  // Wait for the response using typed event handlers
@@ -278,19 +292,41 @@ import { approveAll } from "@microsoft/copilot-sdk";
278
292
 
279
293
  await using session = await client.createSession({
280
294
  model: "gpt-5",
281
- onPermissionRequest: approveAll,
295
+ permissions: {
296
+ onRequest: approveAll,
297
+ },
282
298
  });
283
299
  // session is automatically disconnected when leaving scope
284
300
  ```
285
301
 
286
- When targeting MCP tools configured through `mcpServers`, remember the runtime
287
- tool name is `<server-key>-<tool-name>`. For `availableTools` and
288
- `excludedTools`, prefer `new ToolSet().addMcp("<server-key>-<tool-name>")` or
302
+ When targeting MCP tools configured through `mcp.servers`, remember the runtime
303
+ tool name is `<server-key>-<tool-name>`. For `tools.availableTools` and
304
+ `tools.excludedTools`, prefer `new ToolSet().addMcp("<server-key>-<tool-name>")` or
289
305
  the raw `mcp:<server-key>-<tool-name>` form. For `customAgents[].tools` and
290
306
  `defaultAgent.excludedTools`, use `<server-key>-<tool-name>` directly.
291
307
 
292
308
  ## API Reference
293
309
 
310
+ ### HTTP requests (experimental)
311
+
312
+ Use `client.rpc.fetch.create()` to allocate a handle. Call `fetch.send()` with a required `responseMode`:
313
+
314
+ - `"text"` returns HTTP metadata and complete UTF-8 text, with a default 1 MiB decoded body limit.
315
+ - `"stream"` returns headers immediately. Call `fetch.read()` for base64 chunks until `done`, or `fetch.cancel()` for headers only.
316
+ - `"file"` writes to `destinationPath` on the runtime host. It returns metadata, path, and size; an existing destination fails.
317
+
318
+ Streaming chunks cross JSON-RPC. Prefer file mode for large bodies. Stream and file modes have no default limit; `bodyLimitBytes` accepts zero.
319
+
320
+ All four methods are public to SDK clients, including extension connections. They do not require CLI admission.
321
+
322
+ Only the connection that creates a handle can use it. Use `fetch.cancel()` to cancel a pending request or abandon a stream.
323
+ Completed files survive cancellation and disconnect; the caller deletes them. Failures remove only incomplete request-created files. Remote clients cannot read host paths locally.
324
+ Optional credential contexts retain their original connection and credential authority. Public fetch access does not grant access to another caller's credentials.
325
+
326
+ The [runnable fetch example](examples/fetch.mjs) demonstrates all modes, file survival after disconnect, and caller cleanup against a local fixture.
327
+
328
+ Import `FetchSendParams`, `FetchSendResult`, `FetchTransportErrorData`, `FetchFileErrorData`, and `CredentialContextErrorData` from `@microsoft/copilot-sdk`.
329
+
294
330
  ### CopilotClient
295
331
 
296
332
  #### Constructor
@@ -301,36 +337,37 @@ new CopilotClient(options: CopilotClientOptions)
301
337
 
302
338
  **Options:**
303
339
 
304
- - `connection?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`:
305
- - `RuntimeConnection.forStdio({ path?, args?, env? })` (default) — spawn the runtime and communicate over its stdin/stdout.
306
- - `RuntimeConnection.forTcp({ port?, connectionToken?, path?, args?, env? })` — spawn the runtime as a TCP server.
307
- - `RuntimeConnection.forUri(url, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `gitHubToken`/`useLoggedInUser`). There is no top-level `cliUrl` shortcut; use this factory for URL-based connections.
308
- - `RuntimeConnection.forInProcess()` — host the runtime in-process over its native C ABI (FFI). **Experimental.** Client-level `env`, `telemetry`, and `workingDirectory` are rejected; use supported typed options and configure working directories per session.
309
- - The child-process transports (`forStdio`/`forTcp`) also accept a per-connection `env`. Set it there or via the top-level `env` option — not both (setting both throws).
340
+ - `runtime?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`:
341
+ - `RuntimeConnection.forDefault({ baseDirectory?, sessionIdleTimeoutSeconds? })` — synchronously resolve the deployment default at call time, honoring `COPILOT_SDK_DEFAULT_CONNECTION` (`stdio` or `inprocess`, case-insensitive; empty uses in-process).
342
+ - `RuntimeConnection.forSpawnedStdio({ path?, args?, env?, workingDirectory?, baseDirectory?, sessionIdleTimeoutSeconds? })` — spawn the runtime and communicate over its stdin/stdout.
343
+ - `RuntimeConnection.forSpawnedTcp({ port?, connectionToken?, path?, args?, env?, workingDirectory?, baseDirectory?, sessionIdleTimeoutSeconds? })` — spawn the runtime as a TCP server.
344
+ - `RuntimeConnection.forTcp(host, port, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `github.token`/`github.useLoggedInUser`). There is no top-level `cliUrl` shortcut; use this factory for plaintext TCP connections.
345
+ - `RuntimeConnection.forInProcess({ baseDirectory?, sessionIdleTimeoutSeconds?, runOnUiThread? })` — host the runtime in-process over its native C ABI (FFI). Typed `observability.telemetry` is host-scoped; process `env` and `workingDirectory` are unsupported. Configure working directories per session.
346
+ - Only spawned transports accept `env` and `workingDirectory`; `env` replaces inheritance (`{}` clears it). Owned transports accept `baseDirectory` and `sessionIdleTimeoutSeconds`.
310
347
  - Managed child-process connections materialize the bundled `copilot-runtime` and adjacent `runtime.node`, then launch the wrapper by default. An explicit connection `path` or `COPILOT_CLI_PATH` overrides the bundled runtime.
311
348
  - `mode: "empty" | "coding-agent"` - Required defaulting strategy. Use `"empty"` for multi-user server mode or explicitly select `"coding-agent"` for CLI-like behavior.
312
- - `workingDirectory?: string` - Working directory for the runtime process (default: current process cwd).
313
- - `baseDirectory?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When not set, the runtime defaults to `~/.copilot`. Ignored when connecting via `RuntimeConnection.forUri`.
314
- - `extensionLaunchProvider?: ExtensionLaunchProvider` - Experimental connection-level resolver for extension launch profiles. The client installs the reverse-RPC handler and registers the provider during startup before sessions can be created.
315
- - `installationConfirmationHandler?: InstallationConfirmationHandler` - Experimental connection-global human review for `installations.confirm`. Receives the typed request and independent request/connection cancellation signals, and returns an explicit decision. Does not enable installation capabilities.
316
- - `logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all"` - Log level. When omitted, the runtime uses its own default (currently `"info"`).
317
- - `env?: Record<string, string | undefined>` - Environment variables for the runtime process. When omitted, inherits `process.env`.
349
+ - `runtime.workingDirectory?: string` - Working directory for the runtime process (default: current process cwd).
350
+ - `runtime.baseDirectory?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When not set, the runtime defaults to `~/.copilot`. Available only on owned runtime connections, not `RuntimeConnection.forTcp`.
351
+ - `extensions.launchProvider?: ExtensionLaunchProvider` - Experimental connection-level resolver for extension launch profiles. The client installs the reverse-RPC handler and registers the provider during startup before sessions can be created.
352
+ - `installations.confirmationHandler?: InstallationConfirmationHandler` - Experimental connection-global human review for `installations.confirm`. Receives the typed request and independent request/connection cancellation signals, and returns an explicit decision. Does not enable installation capabilities.
353
+ - `observability.logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all"` - Log level. When omitted, the runtime uses its own default (currently `"info"`).
354
+ - `runtime.env?: Record<string, string | undefined>` - Environment variables for the runtime process. When omitted, inherits `process.env`.
318
355
 
319
356
  Set `COPILOT_TELEMETRY_DISABLED=true` before startup to disable Copilot-owned
320
357
  GitHub and Entra authentication telemetry process-wide, including sessionless
321
- events. Authentication, SDK `onGitHubTelemetry` forwarding, and user-configured
358
+ events. Authentication, SDK `github.onTelemetry` forwarding, and user-configured
322
359
  OpenTelemetry remain unchanged. The value must be exactly `"true"`; restart
323
360
  the process to change it. With `RuntimeConnection.forInProcess()`, set the host
324
- process environment; per-client `env` is rejected. `enableSessionTelemetry: false`
361
+ process environment. `enableSessionTelemetry: false`
325
362
  affects only the session pipeline. The existing native-runtime-only
326
363
  `COPILOT_GITHUB_TELEMETRY_DISABLED=true` remains GitHub-only; the Node CLI host
327
364
  uses the general variable or `--disable-client-telemetry` instead.
328
365
 
329
- - `gitHubToken?: string` - GitHub token for authentication. When provided, takes priority over other auth methods.
330
- - `useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `gitHubToken` is provided). Cannot be used with `RuntimeConnection.forUri`.
331
- - `onListModels?: () => Promise<ModelInfo[]> | ModelInfo[]` - Optional model-list provider, useful when using a custom provider.
332
- - `telemetry?: TelemetryConfig` - OpenTelemetry configuration for the runtime process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
333
- - `onGetTraceContext?: TraceContextProvider` - Advanced: callback for linking your application's own OpenTelemetry spans into the same distributed trace as the runtime's spans. Not needed for normal telemetry collection. See [Telemetry](#telemetry) below.
366
+ - `github.token?: string` - GitHub token for authentication. When provided, takes priority over other auth methods.
367
+ - `github.useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `github.token` is provided). Cannot be used with `RuntimeConnection.forTcp`.
368
+ - `models.onListModels?: () => Promise<Model[]> | Model[]` - Optional model-list provider, useful when using a custom provider.
369
+ - `observability.telemetry?: TelemetryConfig` - OpenTelemetry configuration for the runtime process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
370
+ - `observability.onGetTraceContext?: TraceContextProvider` - Advanced: callback for linking your application's own OpenTelemetry spans into the same distributed trace as the runtime's spans. Not needed for normal telemetry collection. See [Telemetry](#telemetry) below.
334
371
  - `sessionFs?: SessionFsConfig` - Custom session filesystem provider.
335
372
 
336
373
  For a custom provider to serve images to the `view` tool, declare
@@ -345,7 +382,7 @@ when a session is created.
345
382
  Binary reads and writes are limited to 50,330,880 raw bytes (approximately 48 MiB);
346
383
  larger results return a filesystem error before encoding or decoding.
347
384
 
348
- - `sessionIdleTimeoutSeconds?: number` - Server-wide idle timeout for sessions in seconds. Ignored when connecting via `RuntimeConnection.forUri`.
385
+ - `runtime.sessionIdleTimeoutSeconds?: number` - Server-wide idle timeout for sessions in seconds. Available only on owned runtime connections, not `RuntimeConnection.forTcp`.
349
386
 
350
387
  #### Installation confirmation (experimental)
351
388
 
@@ -394,7 +431,7 @@ transport tests do not establish a working installer, live OAuth or restart safe
394
431
 
395
432
  ##### `start(): Promise<void>`
396
433
 
397
- Start the CLI server and establish connection.
434
+ Start the runtime host and establish a connection.
398
435
 
399
436
  ##### `stop(): Promise<Error[]>`
400
437
 
@@ -412,7 +449,7 @@ Retirement releases session-owned tool, hook, auth/input, provider, workflow, ca
412
449
  and transform registrations without changing caller-owned configuration. Late
413
450
  registration and callback dispatch are rejected; callbacks already admitted may finish.
414
451
 
415
- ##### `createSession(config: SessionConfig): Promise<CopilotSession>`
452
+ ##### `createSession(config: CreateSessionOptions): Promise<CopilotSession>`
416
453
 
417
454
  Create a new conversation session.
418
455
 
@@ -420,54 +457,62 @@ Create a new conversation session.
420
457
 
421
458
  - `sessionId?: string` - Custom session ID.
422
459
  - `model?: string` - Model to use ("gpt-5", "claude-sonnet-4.5", etc.). **Required when using custom provider.**
423
- - `capi?: CapiSessionOptions` - Copilot API options. With `model: "auto"`, set `autoTier` to `"efficiency"`, `"balance"`, `"intelligence"`, or `"fast"` to choose a routing preference. `"fast"` is an integrator-only latency preset, not a first-party GitHub Copilot product preference. Requires a runtime with Auto tier support and V2 Auto routing. Omission preserves default behavior. See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for resume semantics.
424
- - `reasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max"` - Reasoning effort level for models that support it. Use `listModels()` to check which models support this option.
425
- - `tools?: Tool[]` - Custom tools exposed to the CLI. Tools without `handler` are declaration-only and must be resolved via pending tool-call RPCs.
460
+ - `github.capi?: CapiSessionOptions` - Copilot API options. With `model: "auto"`, set `autoTier` to `"efficiency"`, `"balance"`, `"intelligence"`, or `"fast"` to choose a routing preference. `"fast"` is an integrator-only latency preset, not a first-party GitHub Copilot product preference. Requires a runtime with Auto tier support and V2 Auto routing. Omission preserves default behavior. See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for resume semantics. For Copilot Fusion, use `model: "fusion"` and set `fusionTier` to `"standard"`, `"high"`, or `"max"`, like the CLI's `--model fusion --fusion-tier <tier>`; the `autoTier` values `"balance"`, `"hydrafusion"`, and `"hydrafusion-max"` that these replace are deprecated. See [Copilot Fusion names](../docs/features/session-persistence.md#copilot-fusion-names).
461
+ - `inference.reasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max"` - Reasoning effort level for models that support it. Use `listModels()` to check which models support this option.
462
+ - `tools.definitions?: Tool[]` - Custom tools exposed to the CLI. Tools without `handler` are declaration-only and must be resolved via pending tool-call RPCs.
426
463
  - `systemMessage?: SystemMessageConfig` - System message customization (see below)
427
- - `infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
464
+ - `state.infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
428
465
  - `workingDirectory?: string` - Working directory for the session (default: runtime process cwd).
429
- - `trustWorkingDirectory?: "session" | "user"` - Grant trust to the canonical working directory during session creation. `"session"` trusts it only for this session; `"user"` persists trust for later sessions. Omit to leave trust unchanged. Not available on resume.
430
- - `refreshCustomInstructions?: boolean` - Invalidates the process-wide custom-instruction discovery cache before creating this session, so instruction-file edits made in the same runtime are read again. Defaults to `false` (cache reuse). Other sessions in this runtime may observe updated instructions on later turns or discovery. This does not watch files or enable disabled instruction loading. Available on `SessionConfig`, not `ResumeSessionConfig`.
431
- - `enableSessionStore?: boolean` - Enables the cross-session store for search and retrieval across sessions. When unset in `"coding-agent"` mode, the runtime default applies (enabled). In `"empty"` mode, defaults to disabled.
432
- - `enableSessionTelemetry?: boolean` - Disables internal session telemetry only when set to `false`. Omission or `true` enables it for eligible GitHub-authenticated sessions, including custom-provider (BYOK) sessions. Host and account policies still control uploads; this is separate from OpenTelemetry configuration.
433
- - `gitHubTokenProvider?: GitHubTokenProvider` - Acquires rotating, session-scoped GitHub tokens. Token results require a positive `expiresIn` value in seconds remaining when the callback completes; production tokens typically last eight hours. Cannot be combined with `gitHubToken`.
434
- - `provider?: ProviderConfig` - Custom API provider configuration (BYOK - Bring Your Own Key). See [Custom Providers](#custom-providers) section.
435
- - `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.
436
- - `onUserInputRequest?: UserInputHandler` - Handler for legacy question-and-answer requests from the agent. Enables the legacy `ask_user` tool. See [User Input Requests](#user-input-requests) section.
437
- - `askUserVariant?: "legacy" | "elicitation"` - Selects the model-facing `ask_user` tool shape when creating or cold-resuming a session. Defaults to `"legacy"`; use `"elicitation"` with `onElicitationRequest`.
438
- - `interactiveUser?: boolean` - Declares that a person types this session's messages, as in an editor chat panel. Enables the runtime's user-message analysis telemetry for user-authored messages; automated messages stay excluded. Defaults to `false`. Ignored for cloud sessions. Re-supply it when cold-resuming a session; it is ignored when resuming a session that is already active.
439
- - `permissionMode?: PermissionMode` - Applies `"manual"`, `"assisted"`, or `"allow-all"` before the session's first turn: before `createSession` returns, and before a resume continues pending work. Uses the same checks as `session.rpc.permissions.setMode`; `session.permissionModeResult` reports whether it was applied and the authoritative mode. Not supported for cloud sessions.
440
- - `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.
441
- - `hooks?: SessionHooks` - Hook handlers for session lifecycle events. See [Session Hooks](#session-hooks) section.
442
- - `skillProvider?: SkillProvider` - **Experimental.** Serves skills from host storage instead of skill directories. Not persisted; pass it again on resume. See [Skill providers](#skill-providers-experimental).
466
+ - `filesystem.trustWorkingDirectory?: "session" | "user"` - Grant trust to the canonical working directory during session creation. `"session"` trusts it only for this session; `"user"` persists trust for later sessions. Omit to leave trust unchanged. Not available on resume.
467
+ - `instructions.refreshCustomInstructions?: boolean` - Invalidates the process-wide custom-instruction discovery cache before creating this session, so instruction-file edits made in the same runtime are read again. Defaults to `false` (cache reuse). Other sessions in this runtime may observe updated instructions on later turns or discovery. This does not watch files or enable disabled instruction loading. Available on `CreateSessionOptions`, not `ResumeSessionOptions`.
468
+ - `state.enableCrossSessionStore?: boolean` - Enables the cross-session store for search and retrieval across sessions. When unset in `"coding-agent"` mode, the runtime default applies (enabled). In `"empty"` mode, defaults to disabled.
469
+ - `github.telemetryEnabled?: boolean` - Disables internal session telemetry only when set to `false`. Omission or `true` enables it for eligible GitHub-authenticated sessions, including custom-provider (BYOK) sessions. Host and account policies still control uploads; this is separate from OpenTelemetry configuration.
470
+ - `github.tokenProvider?: GitHubTokenProvider` - Acquires rotating, session-scoped GitHub tokens. Token results require an `expiresIn` value in seconds remaining when the callback completes, of which more than one hour must still remain after the runtime validates the token; production tokens typically last eight hours. Cannot be combined with `github.token`.
471
+ - `inference.providers?: NamedProviderConfig[]` - Custom API provider configuration (BYOK - Bring Your Own Key). See [Custom Providers](#custom-providers) section.
472
+ - `permissions.onRequest?: 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 `github.fetchManagedSettings` is true. Custom handlers can inspect `managedApprovalRequired` for human-facing confirmation logic. See [Permission Handling](#permission-handling) section.
473
+ - `interaction.onUserInputRequest?: UserInputHandler` - Handler for legacy question-and-answer requests from the agent. Enables the legacy `ask_user` tool. See [User Input Requests](#user-input-requests) section.
474
+ - `interaction.onShellAuthenticationRequest?: ShellAuthenticationHandler` - Handler for passwords and other answers that shell commands run by the agent ask for, such as `sudo -A`, `ssh`, and `git` over HTTPS. The answer goes only to the program that asked; the model never sees it. Without a handler, those commands fail as they do without a terminal. See [Shell password prompts](../docs/features/shell-password-prompts.md).
475
+ - `interaction.askUserVariant?: "legacy" | "elicitation"` - Selects the model-facing `ask_user` tool shape when creating or cold-resuming a session. Defaults to `"legacy"`; use `"elicitation"` with `interaction.onElicitationRequest`.
476
+ - `github.interactiveUser?: boolean` - Declares that a person types this session's messages, as in an editor chat panel. Enables the runtime's user-message analysis telemetry for user-authored messages; automated messages stay excluded. Defaults to `false`. Ignored for cloud sessions. Re-supply it when cold-resuming a session; it is ignored when resuming a session that is already active.
477
+ - `permissions.mode?: PermissionMode` - Applies `"manual"`, `"assisted"`, or `"allow-all"` before the session's first turn: before `createSession` returns, and before a resume continues pending work. Uses the same checks as `session.rpc.permissions.setMode`; `session.permissionModeResult` reports whether it was applied and the authoritative mode. Not supported for cloud sessions.
478
+ - `interaction.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.
479
+ - `hooks.handlers?: SessionHooks` - Hook handlers for session lifecycle events. See [Session Hooks](#session-hooks) section.
480
+ - `skills.provider?: SkillProvider` - **Experimental.** Serves skills from host storage instead of skill directories. Not persisted; pass it again on resume. See [Skill providers](#skill-providers-experimental).
443
481
 
444
482
  <!-- docs-validate: strict -->
445
483
  <!-- docs-validate: hidden -->
484
+
446
485
  ```typescript
447
486
  declare function acquireTokenForHost(host: string): Promise<string>;
448
487
 
449
488
  const session = await client.createSession({
450
- gitHubTokenProvider: async ({ host }) => ({
451
- kind: "token",
452
- accessToken: await acquireTokenForHost(host),
453
- expiresIn: 8 * 60 * 60,
454
- }),
489
+ github: {
490
+ tokenProvider: async ({ host }) => ({
491
+ kind: "token",
492
+ accessToken: await acquireTokenForHost(host),
493
+ expiresIn: 8 * 60 * 60,
494
+ }),
495
+ },
455
496
  });
456
497
  ```
498
+
457
499
  <!-- /docs-validate: hidden -->
500
+
458
501
  ```typescript
459
502
  const session = await client.createSession({
460
- gitHubTokenProvider: async ({ host }) => ({
461
- kind: "token",
462
- accessToken: await acquireTokenForHost(host),
463
- expiresIn: 8 * 60 * 60,
464
- }),
503
+ github: {
504
+ tokenProvider: async ({ host }) => ({
505
+ kind: "token",
506
+ accessToken: await acquireTokenForHost(host),
507
+ expiresIn: 8 * 60 * 60,
508
+ }),
509
+ },
465
510
  });
466
511
  ```
467
512
 
468
513
  Initial acquisition runs during session creation or resume. Cancellation, provider errors, and invalid token responses reject that operation instead of falling back to ambient authentication. Idle sessions refresh only before their next credential-consuming operation; there is no background refresh timer.
469
514
 
470
- ##### `resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>`
515
+ ##### `resumeSession(sessionId: string, config: ResumeSessionOptions): Promise<CopilotSession>`
471
516
 
472
517
  Both create and resume accept experimental `autopilot: AutopilotOptions`, and
473
518
  `session.rpc.options.update({ autopilot: ... })` patches the same policy.
@@ -530,6 +575,7 @@ Request the TUI to switch to displaying the specified session. Only available in
530
575
  Subscribe to a specific session lifecycle event type. Returns an unsubscribe function.
531
576
 
532
577
  <!-- docs-validate: strict -->
578
+
533
579
  ```typescript
534
580
  const unsubscribe = client.onLifecycle("session.foreground", (event) => {
535
581
  console.log(`Session ${event.sessionId} is now in foreground`);
@@ -541,6 +587,7 @@ const unsubscribe = client.onLifecycle("session.foreground", (event) => {
541
587
  Subscribe to all session lifecycle events. Returns an unsubscribe function.
542
588
 
543
589
  <!-- docs-validate: strict -->
590
+
544
591
  ```typescript
545
592
  const unsubscribe = client.onLifecycle((event) => {
546
593
  console.log(`${event.type}: ${event.sessionId}`);
@@ -580,7 +627,7 @@ Send a message to the session. Returns immediately after the message is queued;
580
627
  **Options:**
581
628
 
582
629
  - `prompt: string` - The message/prompt to send
583
- - `source?: MessageSource` - `"user"`, `"system"`, or `` `agent-${string}` `` provenance; omitted by default
630
+ - `source?: MessageSource` - `"user"`, `"system"`, `` `agent-${string}` ``, or `` `automation-${string}` `` provenance; omitted by default. An automation turn defines the session's task like a user message but carries no human authority; see [Message provenance](../docs/features/steering-and-queueing.md#message-provenance).
584
631
  - `attachments?: Array<{type, path, displayName}>` - File attachments
585
632
  - `mode?: "enqueue" | "immediate"` - Delivery mode
586
633
  - `clientTurnId?: string` - Opaque turn ID the runtime adds to MCP `tools/call` requests in this turn as `_meta["com.github.copilot/turnId"]` and echoes on this message's `user.message` event as `clientTurnId` (see [Tool call and turn IDs in `_meta`](../docs/hooks/pre-mcp-tool-call.md#tool-call-and-turn-ids-in-_meta))
@@ -591,6 +638,7 @@ Use `source: "system"` for automated messages from your application:
591
638
 
592
639
  <!-- docs-validate: strict -->
593
640
  <!-- docs-validate: hidden -->
641
+
594
642
  ```typescript
595
643
  import type { CopilotSession } from "@microsoft/copilot-sdk";
596
644
 
@@ -598,7 +646,9 @@ declare const session: CopilotSession;
598
646
 
599
647
  await session.send({ prompt: "Context updated", source: "system" });
600
648
  ```
649
+
601
650
  <!-- /docs-validate: hidden -->
651
+
602
652
  ```typescript
603
653
  await session.send({ prompt: "Context updated", source: "system" });
604
654
  ```
@@ -607,6 +657,7 @@ For a message from another agent, use its trusted sender ID:
607
657
 
608
658
  <!-- docs-validate: strict -->
609
659
  <!-- docs-validate: hidden -->
660
+
610
661
  ```typescript
611
662
  import type { CopilotSession } from "@microsoft/copilot-sdk";
612
663
 
@@ -614,7 +665,9 @@ declare const session: CopilotSession;
614
665
 
615
666
  await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
616
667
  ```
668
+
617
669
  <!-- /docs-validate: hidden -->
670
+
618
671
  ```typescript
619
672
  await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
620
673
  ```
@@ -650,6 +703,7 @@ JSON Schema before sending them:
650
703
 
651
704
  <!-- docs-validate: strict -->
652
705
  <!-- docs-validate: hidden -->
706
+
653
707
  ```typescript
654
708
  import type { CopilotSession } from "@microsoft/copilot-sdk";
655
709
 
@@ -664,7 +718,9 @@ const message = await session.sendAndWait({
664
718
  });
665
719
  console.log(message?.data.content); // JSON text
666
720
  ```
721
+
667
722
  <!-- /docs-validate: hidden -->
723
+
668
724
  ```typescript
669
725
  import { z } from "zod";
670
726
 
@@ -680,6 +736,7 @@ For a typed result, pass the Zod schema as the **second argument** instead:
680
736
 
681
737
  <!-- docs-validate: strict -->
682
738
  <!-- docs-validate: hidden -->
739
+
683
740
  ```typescript
684
741
  import type { CopilotSession } from "@microsoft/copilot-sdk";
685
742
 
@@ -691,7 +748,9 @@ const answerSchema = z.object({ answer: z.number().int() });
691
748
  const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
692
749
  console.log(answer.answer); // number; TResult is inferred from answerSchema
693
750
  ```
751
+
694
752
  <!-- /docs-validate: hidden -->
753
+
695
754
  ```typescript
696
755
  const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
697
756
  console.log(answer.answer); // number; TResult is inferred from answerSchema
@@ -766,6 +825,7 @@ Subscribe to a specific event type. The handler receives properly typed events.
766
825
 
767
826
  <!-- docs-validate: strict -->
768
827
  <!-- docs-validate: hidden -->
828
+
769
829
  ```typescript
770
830
  import type { CopilotSession } from "@microsoft/copilot-sdk";
771
831
 
@@ -785,7 +845,9 @@ session.on("assistant.message_delta", (event) => {
785
845
  process.stdout.write(event.data.deltaContent);
786
846
  });
787
847
  ```
848
+
788
849
  <!-- /docs-validate: hidden -->
850
+
789
851
  ```typescript
790
852
  // Listen for specific event types with full type inference
791
853
  session.on("assistant.message", (event) => {
@@ -808,6 +870,7 @@ Subscribe to all session events. Returns an unsubscribe function.
808
870
 
809
871
  <!-- docs-validate: strict -->
810
872
  <!-- docs-validate: hidden -->
873
+
811
874
  ```typescript
812
875
  import type { CopilotSession } from "@microsoft/copilot-sdk";
813
876
 
@@ -821,7 +884,9 @@ const unsubscribe = session.on((event) => {
821
884
  // Later...
822
885
  unsubscribe();
823
886
  ```
887
+
824
888
  <!-- /docs-validate: hidden -->
889
+
825
890
  ```typescript
826
891
  const unsubscribe = session.on((event) => {
827
892
  // Handle any event type
@@ -838,8 +903,9 @@ Change the model for this session. The new model takes effect for the next messa
838
903
 
839
904
  **Options:**
840
905
 
841
- - `reasoningEffort?: string` - Reasoning effort level
906
+ - `inference.reasoningEffort?: string` - Reasoning effort level
842
907
  - `autoTier?: AutoTier | null` - Auto routing preference to stage together with selecting `auto`. Pass `null` to return to the provider's default Auto routing; omit it to leave the current preference unchanged.
908
+ - `fusionTier?: FusionTier` - Copilot Fusion tier (`"standard"`, `"high"`, or `"max"`) to stage together with selecting `fusion` or `auto`, for example `setModel("fusion", { fusionTier: "high" })`. Cannot be combined with `autoTier`.
843
909
 
844
910
  ##### `setAutoTier(autoTier: AutoTier | null): Promise<ModelSwitchAutoTierResult>`
845
911
 
@@ -851,6 +917,7 @@ Watch for the outcome through the `session.model_change` event on success or the
851
917
 
852
918
  <!-- docs-validate: strict -->
853
919
  <!-- docs-validate: hidden -->
920
+
854
921
  ```typescript
855
922
  import type { CopilotSession } from "@microsoft/copilot-sdk";
856
923
 
@@ -861,7 +928,9 @@ if (result.status === "pending") {
861
928
  // Accepted, but not yet in effect.
862
929
  }
863
930
  ```
931
+
864
932
  <!-- /docs-validate: hidden -->
933
+
865
934
  ```typescript
866
935
  const result = await session.setAutoTier("intelligence");
867
936
  if (result.status === "pending") {
@@ -871,12 +940,21 @@ if (result.status === "pending") {
871
940
 
872
941
  See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for the full lifecycle rules.
873
942
 
943
+ ##### `setFusionTier(fusionTier: FusionTier): Promise<ModelSwitchAutoTierResult>`
944
+
945
+ Change the Copilot Fusion tier without changing the selected model, naming the tier as the CLI's `--fusion-tier` does: `"standard"`, `"high"`, or `"max"`. The runtime resolves the tier to the Auto routing preference it stands for and then handles the request exactly like `setAutoTier`. Use `setAutoTier(null)` to return to the provider's default routing.
946
+
947
+ ```typescript
948
+ const result = await session.setFusionTier("max");
949
+ ```
950
+
874
951
  ##### `rpc.model.getReasoningSummaries(params)` (experimental)
875
952
 
876
953
  Read the current model's reasoning-summary presentation policy without changing session state. Call `session.rpc.model.list()` first to load the model catalog; otherwise the result may have `ready: false`. The request and result types are exported from `@microsoft/copilot-sdk`.
877
954
 
878
955
  <!-- docs-validate: strict -->
879
956
  <!-- docs-validate: hidden -->
957
+
880
958
  ```typescript
881
959
  import type { CopilotSession } from "@microsoft/copilot-sdk";
882
960
 
@@ -891,7 +969,9 @@ const presentation: ModelGetReasoningSummariesRequest = { summariesVisible: fals
891
969
  const policy: ModelGetReasoningSummariesResult =
892
970
  await session.rpc.model.getReasoningSummaries(presentation);
893
971
  ```
972
+
894
973
  <!-- /docs-validate: hidden -->
974
+
895
975
  ```typescript
896
976
  import type {
897
977
  ModelGetReasoningSummariesRequest,
@@ -913,6 +993,7 @@ Once the runtime accepts the replacement, every tool call this session dispatche
913
993
 
914
994
  <!-- docs-validate: strict -->
915
995
  <!-- docs-validate: hidden -->
996
+
916
997
  ```typescript
917
998
  import type { CopilotSession } from "@microsoft/copilot-sdk";
918
999
 
@@ -930,7 +1011,9 @@ await session.setTools([
930
1011
  }),
931
1012
  ]);
932
1013
  ```
1014
+
933
1015
  <!-- /docs-validate: hidden -->
1016
+
934
1017
  ```typescript
935
1018
  await session.setTools([
936
1019
  defineTool("search_issues", {
@@ -961,6 +1044,7 @@ Host capabilities reported when the session was created or resumed. Use this to
961
1044
 
962
1045
  <!-- docs-validate: strict -->
963
1046
  <!-- docs-validate: hidden -->
1047
+
964
1048
  ```typescript
965
1049
  import type { CopilotSession } from "@microsoft/copilot-sdk";
966
1050
 
@@ -970,7 +1054,9 @@ if (session.capabilities.ui?.elicitation) {
970
1054
  const ok = await session.ui.confirm("Deploy?");
971
1055
  }
972
1056
  ```
1057
+
973
1058
  <!-- /docs-validate: hidden -->
1059
+
974
1060
  ```typescript
975
1061
  if (session.capabilities.ui?.elicitation) {
976
1062
  const ok = await session.ui.confirm("Deploy?");
@@ -1088,57 +1174,13 @@ await session.send({ prompt: "What does the most recent jpg in this directory po
1088
1174
  Enable streaming to receive assistant response chunks as they're generated:
1089
1175
 
1090
1176
  <!-- docs-validate: strict -->
1091
- <!-- docs-validate: hidden -->
1092
1177
 
1093
1178
  ```typescript
1094
- import { approveAll } from "@microsoft/copilot-sdk";
1095
-
1096
1179
  const session = await client.createSession({
1097
1180
  model: "gpt-5",
1098
- streaming: true,
1099
- onPermissionRequest: approveAll,
1100
- });
1101
-
1102
- // Wait for completion using typed event handlers
1103
- const done = new Promise<void>((resolve) => {
1104
- session.on("assistant.message_delta", (event) => {
1105
- // Streaming message chunk - print incrementally
1106
- process.stdout.write(event.data.deltaContent);
1107
- });
1108
-
1109
- session.on("assistant.reasoning_delta", (event) => {
1110
- // Streaming reasoning chunk (if model supports reasoning)
1111
- process.stdout.write(event.data.deltaContent);
1112
- });
1113
-
1114
- session.on("assistant.message", (event) => {
1115
- // Final message - complete content
1116
- console.log("\n--- Final message ---");
1117
- console.log(event.data.content);
1118
- });
1119
-
1120
- session.on("assistant.reasoning", (event) => {
1121
- // Final reasoning content (if model supports reasoning)
1122
- console.log("--- Reasoning ---");
1123
- console.log(event.data.content);
1124
- });
1125
-
1126
- session.on("session.idle", () => {
1127
- // Session finished processing
1128
- resolve();
1129
- });
1130
- });
1131
-
1132
- await session.send({ prompt: "Tell me a short story" });
1133
- await done; // Wait for streaming to complete
1134
- ```
1135
-
1136
- <!-- /docs-validate: hidden -->
1137
-
1138
- ```typescript
1139
- const session = await client.createSession({
1140
- model: "gpt-5",
1141
- streaming: true,
1181
+ events: {
1182
+ streaming: true,
1183
+ },
1142
1184
  });
1143
1185
 
1144
1186
  // Wait for completion using typed event handlers
@@ -1193,7 +1235,7 @@ Note: `assistant.message` and `assistant.reasoning` (final events) are always se
1193
1235
  ```typescript
1194
1236
  import { CopilotClient } from "@microsoft/copilot-sdk";
1195
1237
 
1196
- const client = new CopilotClient({ mode: "coding-agent"});
1238
+ const client = new CopilotClient({ mode: "coding-agent" });
1197
1239
 
1198
1240
  // Start manually
1199
1241
  await client.start();
@@ -1219,18 +1261,20 @@ declare function fetchIssue(id: string): Promise<string>;
1219
1261
 
1220
1262
  const session = await client.createSession({
1221
1263
  model: "gpt-5",
1222
- tools: [
1223
- defineTool("lookup_issue", {
1224
- description: "Fetch issue details from our tracker",
1225
- parameters: z.object({
1226
- id: z.string().describe("Issue identifier"),
1264
+ tools: {
1265
+ definitions: [
1266
+ defineTool("lookup_issue", {
1267
+ description: "Fetch issue details from our tracker",
1268
+ parameters: z.object({
1269
+ id: z.string().describe("Issue identifier"),
1270
+ }),
1271
+ handler: async ({ id }) => {
1272
+ const issue = await fetchIssue(id);
1273
+ return issue;
1274
+ },
1227
1275
  }),
1228
- handler: async ({ id }) => {
1229
- const issue = await fetchIssue(id);
1230
- return issue;
1231
- },
1232
- }),
1233
- ],
1276
+ ],
1277
+ },
1234
1278
  });
1235
1279
  ```
1236
1280
 
@@ -1238,22 +1282,24 @@ const session = await client.createSession({
1238
1282
 
1239
1283
  ```ts
1240
1284
  import { z } from "zod";
1241
- import { CopilotClient, defineTool } from "@microsoft/copilot-sdk";
1285
+ import { defineTool } from "@microsoft/copilot-sdk";
1242
1286
 
1243
1287
  const session = await client.createSession({
1244
1288
  model: "gpt-5",
1245
- tools: [
1246
- defineTool("lookup_issue", {
1247
- description: "Fetch issue details from our tracker",
1248
- parameters: z.object({
1249
- id: z.string().describe("Issue identifier"),
1289
+ tools: {
1290
+ definitions: [
1291
+ defineTool("lookup_issue", {
1292
+ description: "Fetch issue details from our tracker",
1293
+ parameters: z.object({
1294
+ id: z.string().describe("Issue identifier"),
1295
+ }),
1296
+ handler: async ({ id }) => {
1297
+ const issue = await fetchIssue(id);
1298
+ return issue;
1299
+ },
1250
1300
  }),
1251
- handler: async ({ id }) => {
1252
- const issue = await fetchIssue(id);
1253
- return issue;
1254
- },
1255
- }),
1256
- ],
1301
+ ],
1302
+ },
1257
1303
  });
1258
1304
  ```
1259
1305
 
@@ -1404,17 +1450,21 @@ Register slash commands so that users of the CLI's TUI can invoke custom actions
1404
1450
  import { approveAll } from "@microsoft/copilot-sdk";
1405
1451
 
1406
1452
  const session = await client.createSession({
1407
- onPermissionRequest: approveAll,
1408
- commands: [
1409
- {
1410
- name: "deploy",
1411
- description: "Deploy the app to production",
1412
- handler: async ({ commandName, args }) => {
1413
- console.log(`Deploying with args: ${args}`);
1414
- // Do work here — any thrown error is reported back to the CLI
1453
+ permissions: {
1454
+ onRequest: approveAll,
1455
+ },
1456
+ interaction: {
1457
+ commands: [
1458
+ {
1459
+ name: "deploy",
1460
+ description: "Deploy the app to production",
1461
+ handler: async ({ commandName, args }) => {
1462
+ console.log(`Deploying with args: ${args}`);
1463
+ // Do work here — any thrown error is reported back to the CLI
1464
+ },
1415
1465
  },
1416
- },
1417
- ],
1466
+ ],
1467
+ },
1418
1468
  });
1419
1469
  ```
1420
1470
 
@@ -1422,17 +1472,21 @@ const session = await client.createSession({
1422
1472
 
1423
1473
  ```ts
1424
1474
  const session = await client.createSession({
1425
- onPermissionRequest: approveAll,
1426
- commands: [
1427
- {
1428
- name: "deploy",
1429
- description: "Deploy the app to production",
1430
- handler: async ({ commandName, args }) => {
1431
- console.log(`Deploying with args: ${args}`);
1432
- // Do work here — any thrown error is reported back to the CLI
1475
+ permissions: {
1476
+ onRequest: approveAll,
1477
+ },
1478
+ interaction: {
1479
+ commands: [
1480
+ {
1481
+ name: "deploy",
1482
+ description: "Deploy the app to production",
1483
+ handler: async ({ commandName, args }) => {
1484
+ console.log(`Deploying with args: ${args}`);
1485
+ // Do work here — any thrown error is reported back to the CLI
1486
+ },
1433
1487
  },
1434
- },
1435
- ],
1488
+ ],
1489
+ },
1436
1490
  });
1437
1491
  ```
1438
1492
 
@@ -1442,7 +1496,7 @@ Commands are sent to the CLI on both `createSession` and `resumeSession`, so you
1442
1496
 
1443
1497
  ### UI Elicitation
1444
1498
 
1445
- When the session has elicitation support — either from the CLI's TUI or from another client that registered an `onElicitationRequest` handler (see [Elicitation Requests](#elicitation-requests)) — the SDK can request interactive form dialogs from the user. The `session.ui` object provides convenience methods built on a single generic `elicitation` RPC.
1499
+ When the session has elicitation support — either from the CLI's TUI or from another client that registered an `interaction.onElicitationRequest` handler (see [Elicitation Requests](#elicitation-requests)) — the SDK can request interactive form dialogs from the user. The `session.ui` object provides convenience methods built on a single generic `elicitation` RPC.
1446
1500
 
1447
1501
  > **Capability check:** Elicitation is only available when at least one connected participant advertises support. Always check `session.capabilities.ui?.elicitation` before calling UI methods — this property updates automatically as participants join and leave.
1448
1502
 
@@ -1452,7 +1506,11 @@ When the session has elicitation support — either from the CLI's TUI or from a
1452
1506
  ```ts
1453
1507
  import { approveAll } from "@microsoft/copilot-sdk";
1454
1508
 
1455
- const session = await client.createSession({ onPermissionRequest: approveAll });
1509
+ const session = await client.createSession({
1510
+ permissions: {
1511
+ onRequest: approveAll,
1512
+ },
1513
+ });
1456
1514
 
1457
1515
  if (session.capabilities.ui?.elicitation) {
1458
1516
  // Confirm dialog — returns boolean
@@ -1488,7 +1546,11 @@ if (session.capabilities.ui?.elicitation) {
1488
1546
  <!-- /docs-validate: hidden -->
1489
1547
 
1490
1548
  ```ts
1491
- const session = await client.createSession({ onPermissionRequest: approveAll });
1549
+ const session = await client.createSession({
1550
+ permissions: {
1551
+ onRequest: approveAll,
1552
+ },
1553
+ });
1492
1554
 
1493
1555
  if (session.capabilities.ui?.elicitation) {
1494
1556
  // Confirm dialog — returns boolean
@@ -1628,17 +1690,21 @@ console.log(session.workspacePath);
1628
1690
  // Custom thresholds
1629
1691
  const tuned = await client.createSession({
1630
1692
  model: "gpt-5",
1631
- infiniteSessions: {
1632
- enabled: true,
1633
- backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1634
- bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1693
+ state: {
1694
+ infiniteSessions: {
1695
+ enabled: true,
1696
+ backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1697
+ bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1698
+ },
1635
1699
  },
1636
1700
  });
1637
1701
 
1638
1702
  // Disable infinite sessions
1639
1703
  const disabled = await client.createSession({
1640
1704
  model: "gpt-5",
1641
- infiniteSessions: { enabled: false },
1705
+ state: {
1706
+ infiniteSessions: { enabled: false },
1707
+ },
1642
1708
  });
1643
1709
  ```
1644
1710
 
@@ -1655,17 +1721,21 @@ console.log(session.workspacePath);
1655
1721
  // Custom thresholds
1656
1722
  const tuned = await client.createSession({
1657
1723
  model: "gpt-5",
1658
- infiniteSessions: {
1659
- enabled: true,
1660
- backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1661
- bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1724
+ state: {
1725
+ infiniteSessions: {
1726
+ enabled: true,
1727
+ backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1728
+ bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1729
+ },
1662
1730
  },
1663
1731
  });
1664
1732
 
1665
1733
  // Disable infinite sessions
1666
1734
  const disabled = await client.createSession({
1667
1735
  model: "gpt-5",
1668
- infiniteSessions: { enabled: false },
1736
+ state: {
1737
+ infiniteSessions: { enabled: false },
1738
+ },
1669
1739
  });
1670
1740
  ```
1671
1741
 
@@ -1690,13 +1760,17 @@ For more background, see [About GitHub Copilot Memory](https://docs.github.com/e
1690
1760
  // Enable memory for a session
1691
1761
  const enabled = await client.createSession({
1692
1762
  model: "gpt-5",
1693
- memory: { enabled: true },
1763
+ state: {
1764
+ memory: { enabled: true },
1765
+ },
1694
1766
  });
1695
1767
 
1696
1768
  // Disable memory for a session
1697
1769
  const disabled = await client.createSession({
1698
1770
  model: "gpt-5",
1699
- memory: { enabled: false },
1771
+ state: {
1772
+ memory: { enabled: false },
1773
+ },
1700
1774
  });
1701
1775
  ```
1702
1776
 
@@ -1706,13 +1780,17 @@ const disabled = await client.createSession({
1706
1780
  // Enable memory for a session
1707
1781
  const enabled = await client.createSession({
1708
1782
  model: "gpt-5",
1709
- memory: { enabled: true },
1783
+ state: {
1784
+ memory: { enabled: true },
1785
+ },
1710
1786
  });
1711
1787
 
1712
1788
  // Disable memory for a session
1713
1789
  const disabled = await client.createSession({
1714
1790
  model: "gpt-5",
1715
- memory: { enabled: false },
1791
+ state: {
1792
+ memory: { enabled: false },
1793
+ },
1716
1794
  });
1717
1795
  ```
1718
1796
 
@@ -1744,8 +1822,12 @@ const skillProvider: SkillProvider = {
1744
1822
  };
1745
1823
 
1746
1824
  const session = await client.createSession({
1747
- onPermissionRequest: approveAll,
1748
- skillProvider,
1825
+ permissions: {
1826
+ onRequest: approveAll,
1827
+ },
1828
+ skills: {
1829
+ provider: skillProvider,
1830
+ },
1749
1831
  });
1750
1832
  ```
1751
1833
 
@@ -1762,8 +1844,12 @@ const skillProvider: SkillProvider = {
1762
1844
  };
1763
1845
 
1764
1846
  const session = await client.createSession({
1765
- onPermissionRequest: approveAll,
1766
- skillProvider,
1847
+ permissions: {
1848
+ onRequest: approveAll,
1849
+ },
1850
+ skills: {
1851
+ provider: skillProvider,
1852
+ },
1767
1853
  });
1768
1854
  ```
1769
1855
 
@@ -1834,7 +1920,11 @@ const session = await client.createSession({
1834
1920
  ```typescript
1835
1921
  import { approveAll } from "@microsoft/copilot-sdk";
1836
1922
 
1837
- const session = await client.createSession({ onPermissionRequest: approveAll });
1923
+ const session = await client.createSession({
1924
+ permissions: {
1925
+ onRequest: approveAll,
1926
+ },
1927
+ });
1838
1928
 
1839
1929
  await session.send({
1840
1930
  prompt: "Analyze this file",
@@ -1867,9 +1957,9 @@ await session.send({
1867
1957
 
1868
1958
  The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own Key), including local providers like Ollama. When using a custom provider, you must specify the `model` explicitly.
1869
1959
 
1870
- **ProviderConfig:**
1960
+ **NamedProviderConfig:**
1871
1961
 
1872
- - `type?: "openai" | "azure" | "anthropic"` - Provider type (default: "openai")
1962
+ - `type?: "openai" | "azure" | "anthropic" | "google"` - Provider type (default: "openai"). `"google"` (experimental) uses Google's native Gemini Interactions API.
1873
1963
  - `baseUrl: string` - API endpoint URL (required)
1874
1964
  - `apiKey?: string` - API key (optional for local providers like Ollama)
1875
1965
  - `bearerToken?: string` - Bearer token for authentication (takes precedence over apiKey)
@@ -1882,11 +1972,19 @@ The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own K
1882
1972
 
1883
1973
  ```typescript
1884
1974
  const session = await client.createSession({
1885
- model: "deepseek-coder-v2:16b", // Required when using custom provider
1886
- provider: {
1887
- type: "openai",
1888
- baseUrl: "http://localhost:11434/v1", // Ollama endpoint
1889
- // apiKey not required for Ollama
1975
+ model: "deepseek-coder-v2:16b",
1976
+ github: { capi: { enabled: false } },
1977
+ inference: {
1978
+ // Required when using custom provider
1979
+ defaultProvider: "byok",
1980
+ providers: [
1981
+ {
1982
+ name: "byok",
1983
+ type: "openai",
1984
+ baseUrl: "http://localhost:11434/v1", // Ollama endpoint
1985
+ // apiKey not required for Ollama
1986
+ },
1987
+ ],
1890
1988
  },
1891
1989
  });
1892
1990
 
@@ -1900,10 +1998,17 @@ await session.sendAndWait({ prompt: "Hello!" });
1900
1998
  ```typescript
1901
1999
  const session = await client.createSession({
1902
2000
  model: "gpt-4",
1903
- provider: {
1904
- type: "openai",
1905
- baseUrl: "https://my-api.example.com/v1",
1906
- apiKey: process.env.MY_API_KEY,
2001
+ github: { capi: { enabled: false } },
2002
+ inference: {
2003
+ defaultProvider: "byok",
2004
+ providers: [
2005
+ {
2006
+ name: "byok",
2007
+ type: "openai",
2008
+ baseUrl: "https://my-api.example.com/v1",
2009
+ apiKey: process.env.MY_API_KEY,
2010
+ },
2011
+ ],
1907
2012
  },
1908
2013
  });
1909
2014
  ```
@@ -1915,13 +2020,20 @@ const session = await client.createSession({
1915
2020
  ```typescript
1916
2021
  const session = await client.createSession({
1917
2022
  model: "gpt-4",
1918
- provider: {
1919
- type: "azure", // Must be "azure" for Azure endpoints, NOT "openai"
1920
- baseUrl: "https://my-resource.openai.azure.com", // Just the host, no path
1921
- apiKey: process.env.AZURE_OPENAI_KEY,
1922
- azure: {
1923
- apiVersion: "2024-10-21",
1924
- },
2023
+ github: { capi: { enabled: false } },
2024
+ inference: {
2025
+ defaultProvider: "byok",
2026
+ providers: [
2027
+ {
2028
+ name: "byok",
2029
+ type: "azure", // Must be "azure" for Azure endpoints, NOT "openai"
2030
+ baseUrl: "https://my-resource.openai.azure.com", // Just the host, no path
2031
+ apiKey: process.env.AZURE_OPENAI_KEY,
2032
+ azure: {
2033
+ apiVersion: "2024-10-21",
2034
+ },
2035
+ },
2036
+ ],
1925
2037
  },
1926
2038
  });
1927
2039
  ```
@@ -1934,7 +2046,7 @@ const session = await client.createSession({
1934
2046
 
1935
2047
  ## Telemetry
1936
2048
 
1937
- The SDK supports OpenTelemetry for distributed tracing. Provide a `telemetry` config to enable trace export from the CLI process — this is all most users need:
2049
+ The SDK supports OpenTelemetry for distributed tracing. Provide a `telemetry` config to enable trace export from the runtime — this is all most users need:
1938
2050
 
1939
2051
  <!-- docs-validate: strict -->
1940
2052
 
@@ -1943,13 +2055,15 @@ import { CopilotClient } from "@microsoft/copilot-sdk";
1943
2055
 
1944
2056
  const client = new CopilotClient({
1945
2057
  mode: "coding-agent",
1946
- telemetry: {
1947
- otlpEndpoint: "http://localhost:4318",
2058
+ observability: {
2059
+ telemetry: {
2060
+ otlpEndpoint: "http://localhost:4318",
2061
+ },
1948
2062
  },
1949
2063
  });
1950
2064
  ```
1951
2065
 
1952
- With just this configuration, the CLI emits spans for every session, message, and tool call to your collector. No additional dependencies or setup required.
2066
+ With just this configuration, the runtime emits spans for every session, message, and tool call to your collector. No additional dependencies or setup required.
1953
2067
 
1954
2068
  **TelemetryConfig options:**
1955
2069
 
@@ -1962,7 +2076,7 @@ With just this configuration, the CLI emits spans for every session, message, an
1962
2076
 
1963
2077
  ### Advanced: Trace Context Propagation
1964
2078
 
1965
- > **You don't need this for normal telemetry collection.** The `telemetry` config above is sufficient to get full traces from the CLI.
2079
+ > **You don't need this for normal telemetry collection.** The `telemetry` config above is sufficient to get full traces from the runtime.
1966
2080
 
1967
2081
  `onGetTraceContext` is only needed if your application creates its own OpenTelemetry spans and you want them to appear in the **same distributed trace** as the CLI's spans — for example, to nest a "handle tool call" span inside the CLI's "execute tool" span, or to show the SDK call as a child of your application's request-handling span.
1968
2082
 
@@ -1974,11 +2088,13 @@ import { propagation, context } from "@opentelemetry/api";
1974
2088
 
1975
2089
  const client = new CopilotClient({
1976
2090
  mode: "coding-agent",
1977
- telemetry: { otlpEndpoint: "http://localhost:4318" },
1978
- onGetTraceContext: () => {
1979
- const carrier: Record<string, string> = {};
1980
- propagation.inject(context.active(), carrier);
1981
- return carrier;
2091
+ observability: {
2092
+ telemetry: { otlpEndpoint: "http://localhost:4318" },
2093
+ onGetTraceContext: () => {
2094
+ const carrier: Record<string, string> = {};
2095
+ propagation.inject(context.active(), carrier);
2096
+ return carrier;
2097
+ },
1982
2098
  },
1983
2099
  });
1984
2100
  ```
@@ -1987,7 +2103,7 @@ Inbound trace context from the CLI is available on the `ToolInvocation` object p
1987
2103
 
1988
2104
  ## Permission Handling
1989
2105
 
1990
- An `onPermissionRequest` handler is optional when you create or resume a session. When provided, it is called before the agent executes each tool (file writes, shell commands, custom tools, etc.) and returns a decision. When omitted, permission requests are emitted as events and left pending for the consumer to resolve with the pending permission RPC.
2106
+ An `permissions.onRequest` handler is optional when you create or resume a session. When provided, it is called before the agent executes each tool (file writes, shell commands, custom tools, etc.) and returns a decision. When omitted, permission requests are emitted as events and left pending for the consumer to resolve with the pending permission RPC.
1991
2107
 
1992
2108
  Callbacks receive optional derived prompt context as `invocation.promptRequest`. The raw request's `managedApprovalRequired` remains managed-policy provenance and enforces one-shot restrictions. Only derived `commands`, `read`, `write`, `url`, and `workflow` prompts can clear the human requirement after Assisted approval; for missing or other prompt kinds, keep the raw marker authoritative.
1993
2109
 
@@ -2003,7 +2119,9 @@ import { approveAll } from "@microsoft/copilot-sdk";
2003
2119
 
2004
2120
  const session = await client.createSession({
2005
2121
  model: "gpt-5",
2006
- onPermissionRequest: approveAll,
2122
+ permissions: {
2123
+ onRequest: approveAll,
2124
+ },
2007
2125
  });
2008
2126
  ```
2009
2127
 
@@ -2014,11 +2132,13 @@ import { CopilotClient, approveAll } from "@microsoft/copilot-sdk";
2014
2132
 
2015
2133
  const session = await client.createSession({
2016
2134
  model: "gpt-5",
2017
- onPermissionRequest: approveAll,
2135
+ permissions: {
2136
+ onRequest: approveAll,
2137
+ },
2018
2138
  });
2019
2139
  ```
2020
2140
 
2021
- 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.
2141
+ When `github.fetchManagedSettings` is true for the session, `approveAll` throws. Use a custom handler for managed sessions; request-level `managedApprovalRequired` remains available for human-facing confirmation logic.
2022
2142
 
2023
2143
  ### Custom Permission Handler
2024
2144
 
@@ -2031,33 +2151,35 @@ import type { PermissionRequest, PermissionRequestResult } from "@microsoft/copi
2031
2151
 
2032
2152
  const session = await client.createSession({
2033
2153
  model: "gpt-5",
2034
- onPermissionRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
2035
- if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
2036
- // Leave the request pending for the host's human-facing confirmation flow.
2037
- return { kind: "no-result" };
2038
- }
2039
-
2040
- // request.kind — what type of operation is being requested:
2041
- // "shell" — executing a shell command
2042
- // "write" — writing or editing a file
2043
- // "read" — reading a file
2044
- // "mcp" — calling an MCP tool
2045
- // "custom-tool" — calling one of your registered tools
2046
- // "url" — fetching a URL
2047
- // "memory" — storing or retrieving persistent session memory
2048
- // "hook" — invoking a server-side hook or integration
2049
- // (additional kinds may be added; include a default case in handlers)
2050
- // request.toolCallId — the tool call that triggered this request
2051
- // request.toolName — name of the tool (for custom-tool / mcp)
2052
- // request.fileName — file being written (for write)
2053
- // request.fullCommandText — full shell command (for shell)
2054
-
2055
- if (request.kind === "shell") {
2056
- // Deny shell commands, optionally telling the model why
2057
- return { kind: "reject", feedback: "Shell commands are not allowed." };
2058
- }
2059
-
2060
- return { kind: "approve-once" };
2154
+ permissions: {
2155
+ onRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
2156
+ if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
2157
+ // Leave the request pending for the host's human-facing confirmation flow.
2158
+ return { kind: "no-result" };
2159
+ }
2160
+
2161
+ // request.kind — what type of operation is being requested:
2162
+ // "shell" — executing a shell command
2163
+ // "write" — writing or editing a file
2164
+ // "read" — reading a file
2165
+ // "mcp" — calling an MCP tool
2166
+ // "custom-tool" — calling one of your registered tools
2167
+ // "url" — fetching a URL
2168
+ // "memory" — storing or retrieving persistent session memory
2169
+ // "hook" — invoking a server-side hook or integration
2170
+ // (additional kinds may be added; include a default case in handlers)
2171
+ // request.toolCallId — the tool call that triggered this request
2172
+ // request.toolName — name of the tool (for custom-tool / mcp)
2173
+ // request.fileName — file being written (for write)
2174
+ // request.fullCommandText — full shell command (for shell)
2175
+
2176
+ if (request.kind === "shell") {
2177
+ // Deny shell commands, optionally telling the model why
2178
+ return { kind: "reject", feedback: "Shell commands are not allowed." };
2179
+ }
2180
+
2181
+ return { kind: "approve-once" };
2182
+ },
2061
2183
  },
2062
2184
  });
2063
2185
  ```
@@ -2158,7 +2280,7 @@ The handler must return one of the `PermissionDecision` shapes (or `{ kind: "no-
2158
2280
 
2159
2281
  ### Resuming Sessions
2160
2282
 
2161
- You may pass `onPermissionRequest` when resuming a session too:
2283
+ You may pass `permissions.onRequest` when resuming a session too:
2162
2284
 
2163
2285
  <!-- docs-validate: strict -->
2164
2286
  <!-- docs-validate: hidden -->
@@ -2167,7 +2289,9 @@ You may pass `onPermissionRequest` when resuming a session too:
2167
2289
  import { approveAll } from "@microsoft/copilot-sdk";
2168
2290
 
2169
2291
  const session = await client.resumeSession("session-id", {
2170
- onPermissionRequest: approveAll,
2292
+ permissions: {
2293
+ onRequest: approveAll,
2294
+ },
2171
2295
  });
2172
2296
  ```
2173
2297
 
@@ -2175,7 +2299,9 @@ const session = await client.resumeSession("session-id", {
2175
2299
 
2176
2300
  ```typescript
2177
2301
  const session = await client.resumeSession("session-id", {
2178
- onPermissionRequest: approveAll,
2302
+ permissions: {
2303
+ onRequest: approveAll,
2304
+ },
2179
2305
  });
2180
2306
  ```
2181
2307
 
@@ -2185,36 +2311,67 @@ To let a specific custom tool bypass the permission prompt entirely, set `skipPe
2185
2311
 
2186
2312
  ## User Input Requests
2187
2313
 
2188
- Enable the legacy question-and-answer `ask_user` tool by providing an `onUserInputRequest` handler:
2314
+ Enable the legacy question-and-answer `ask_user` tool by providing an `interaction.onUserInputRequest` handler:
2315
+
2316
+ <!-- docs-validate: strict -->
2317
+
2318
+ ```typescript
2319
+ const session = await client.createSession({
2320
+ model: "gpt-5",
2321
+ interaction: {
2322
+ onUserInputRequest: async (request, invocation) => {
2323
+ // request.question - The question to ask
2324
+ // request.choices - Optional array of choices for multiple choice
2325
+ // request.allowFreeform - Whether freeform input is allowed (default: true)
2326
+ // request.requestId - Runtime ID of the pending request (absent on older runtimes)
2327
+
2328
+ console.log(`Agent asks: ${request.question}`);
2329
+ if (request.choices) {
2330
+ console.log(`Choices: ${request.choices.join(", ")}`);
2331
+ }
2332
+
2333
+ // Return the user's response
2334
+ return {
2335
+ answer: "User's answer here",
2336
+ wasFreeform: true, // Whether the answer was freeform (not from choices)
2337
+ };
2338
+ },
2339
+ },
2340
+ });
2341
+ ```
2342
+
2343
+ ### Reporting a person's answers
2344
+
2345
+ When a person answers a prompt in your UI, label the result with `createAttributedResult` so Assisted Permissions can treat the answer as the person's own authority. The same label works for permission, user-input, plan-review, and elicitation handlers:
2189
2346
 
2190
2347
  <!-- docs-validate: strict -->
2191
2348
 
2192
2349
  ```typescript
2350
+ import { createAttributedResult, type PermissionDecisionContext } from "@microsoft/copilot-sdk";
2351
+
2352
+ const personAnswered: PermissionDecisionContext = {
2353
+ source: "human_response",
2354
+ responseCapability: "interactive",
2355
+ surface: "sdk",
2356
+ outcome: "prompted_user",
2357
+ };
2358
+
2193
2359
  const session = await client.createSession({
2194
2360
  model: "gpt-5",
2195
- onUserInputRequest: async (request, invocation) => {
2196
- // request.question - The question to ask
2197
- // request.choices - Optional array of choices for multiple choice
2198
- // request.allowFreeform - Whether freeform input is allowed (default: true)
2199
- // request.requestId - Runtime ID of the pending request (absent on older runtimes)
2200
-
2201
- console.log(`Agent asks: ${request.question}`);
2202
- if (request.choices) {
2203
- console.log(`Choices: ${request.choices.join(", ")}`);
2204
- }
2205
-
2206
- // Return the user's response
2207
- return {
2208
- answer: "User's answer here",
2209
- wasFreeform: true, // Whether the answer was freeform (not from choices)
2210
- };
2361
+ interaction: {
2362
+ onUserInputRequest: async (request) =>
2363
+ createAttributedResult({ answer: "Only src/app.ts", wasFreeform: true }, personAnswered),
2364
+ onExitPlanModeRequest: async () =>
2365
+ createAttributedResult({ approved: true, selectedAction: "interactive" }, personAnswered),
2211
2366
  },
2212
2367
  });
2213
2368
  ```
2214
2369
 
2370
+ Label a person's declines and dismissals too; the runtime decides which answers carry authority. It accepts the label only from the connection that owns the session, so other connections' answers still settle, without it. Leave automated answers unlabeled.
2371
+
2215
2372
  ## Elicitation Requests
2216
2373
 
2217
- Register an `onElicitationRequest` handler to let your client act as an elicitation provider — presenting form-based UI dialogs on behalf of the agent. When provided, the server notifies your client whenever a tool or MCP server needs structured user input.
2374
+ Register an `interaction.onElicitationRequest` handler to let your client act as an elicitation provider — presenting form-based UI dialogs on behalf of the agent. When provided, the server notifies your client whenever a tool or MCP server needs structured user input.
2218
2375
 
2219
2376
  <!-- docs-validate: strict -->
2220
2377
 
@@ -2223,22 +2380,26 @@ import { approveAll } from "@microsoft/copilot-sdk";
2223
2380
 
2224
2381
  const session = await client.createSession({
2225
2382
  model: "gpt-5",
2226
- onPermissionRequest: approveAll,
2227
- askUserVariant: "elicitation",
2228
- onElicitationRequest: async (context) => {
2229
- // context.sessionId - Session that triggered the request
2230
- // context.message - Description of what information is needed
2231
- // context.requestedSchema - JSON Schema describing the form fields
2232
- // context.mode - "form" (structured input) or "url" (browser redirect)
2233
- // context.elicitationSource - Origin of the request (e.g. MCP server name)
2234
-
2235
- console.log(`Elicitation from ${context.elicitationSource}: ${context.message}`);
2236
-
2237
- // Present UI to the user and collect their response...
2238
- return {
2239
- action: "accept", // "accept", "decline", or "cancel"
2240
- content: { region: "us-east", dryRun: true },
2241
- };
2383
+ permissions: {
2384
+ onRequest: approveAll,
2385
+ },
2386
+ interaction: {
2387
+ askUserVariant: "elicitation",
2388
+ onElicitationRequest: async (context) => {
2389
+ // context.sessionId - Session that triggered the request
2390
+ // context.message - Description of what information is needed
2391
+ // context.requestedSchema - JSON Schema describing the form fields
2392
+ // context.mode - "form" (structured input) or "url" (browser redirect)
2393
+ // context.elicitationSource - Origin of the request (e.g. MCP server name)
2394
+
2395
+ console.log(`Elicitation from ${context.elicitationSource}: ${context.message}`);
2396
+
2397
+ // Present UI to the user and collect their response...
2398
+ return {
2399
+ action: "accept", // "accept", "decline", or "cancel"
2400
+ content: { region: "us-east", dryRun: true },
2401
+ };
2402
+ },
2242
2403
  },
2243
2404
  });
2244
2405
 
@@ -2249,7 +2410,7 @@ console.log(session.capabilities.ui?.elicitation); // true
2249
2410
  Set `askUserVariant: "elicitation"` to expose the structured form as the model's
2250
2411
  `ask_user` tool. Omit it to retain the legacy SDK behavior.
2251
2412
 
2252
- When `onElicitationRequest` is provided, the SDK sends `requestElicitation: true` during session create/resume, which enables `session.capabilities.ui.elicitation` on the session.
2413
+ When `interaction.onElicitationRequest` is provided, the SDK sends `requestElicitation: true` during session create/resume, which enables `session.capabilities.ui.elicitation` on the session.
2253
2414
 
2254
2415
  In multi-client scenarios:
2255
2416
 
@@ -2270,87 +2431,89 @@ declare function needsMoreWork(): boolean;
2270
2431
  const session = await client.createSession({
2271
2432
  model: "gpt-5",
2272
2433
  hooks: {
2273
- // Called before each tool execution
2274
- onPreToolUse: async (input, invocation) => {
2275
- console.log(`About to run tool: ${input.toolName}`);
2276
- // Return permission decision and optionally modify args
2277
- return {
2278
- permissionDecision: "allow", // "allow", "deny", or "ask"
2279
- modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2280
- additionalContext: "Extra context for the model",
2281
- };
2282
- },
2283
-
2284
- // Called after each successful tool execution
2285
- onPostToolUse: async (input, invocation) => {
2286
- console.log(`Tool ${input.toolName} completed`);
2287
- // Optionally modify the result or add context
2288
- return {
2289
- additionalContext: "Post-execution notes",
2290
- };
2291
- },
2434
+ handlers: {
2435
+ // Called before each tool execution
2436
+ onPreToolUse: async (input, invocation) => {
2437
+ console.log(`About to run tool: ${input.toolName}`);
2438
+ // Return permission decision and optionally modify args
2439
+ return {
2440
+ permissionDecision: "allow", // "allow", "deny", or "ask"
2441
+ modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2442
+ additionalContext: "Extra context for the model",
2443
+ };
2444
+ },
2292
2445
 
2293
- // Called after a tool execution whose result was "failure".
2294
- // onPostToolUse does NOT fire for failed tool calls — register this
2295
- // hook to observe them. Input includes `error` (the failure message
2296
- // extracted from the tool's result), not the full result object.
2297
- onPostToolUseFailure: async (input, invocation) => {
2298
- console.log(`Tool ${input.toolName} failed: ${input.error}`);
2299
- // Optionally append hidden guidance to the model.
2300
- return { additionalContext: "Suggest checking inputs and retrying." };
2301
- },
2446
+ // Called after each successful tool execution
2447
+ onPostToolUse: async (input, invocation) => {
2448
+ console.log(`Tool ${input.toolName} completed`);
2449
+ // Optionally modify the result or add context
2450
+ return {
2451
+ additionalContext: "Post-execution notes",
2452
+ };
2453
+ },
2302
2454
 
2303
- // Called when user submits a prompt
2304
- onUserPromptSubmitted: async (input, invocation) => {
2305
- console.log(`User prompt: ${input.prompt}`);
2306
- return {
2307
- modifiedPrompt: input.prompt, // Optionally modify the prompt
2308
- };
2309
- },
2455
+ // Called after a tool execution whose result was "failure".
2456
+ // onPostToolUse does NOT fire for failed tool calls — register this
2457
+ // hook to observe them. Input includes `error` (the failure message
2458
+ // extracted from the tool's result), not the full result object.
2459
+ onPostToolUseFailure: async (input, invocation) => {
2460
+ console.log(`Tool ${input.toolName} failed: ${input.error}`);
2461
+ // Optionally append hidden guidance to the model.
2462
+ return { additionalContext: "Suggest checking inputs and retrying." };
2463
+ },
2310
2464
 
2311
- // Called when session starts
2312
- onSessionStart: async (input, invocation) => {
2313
- console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2314
- return {
2315
- additionalContext: "Session initialization context",
2316
- };
2317
- },
2465
+ // Called when user submits a prompt
2466
+ onUserPromptSubmitted: async (input, invocation) => {
2467
+ console.log(`User prompt: ${input.prompt}`);
2468
+ return {
2469
+ modifiedPrompt: input.prompt, // Optionally modify the prompt
2470
+ };
2471
+ },
2318
2472
 
2319
- // Called when session ends
2320
- onSessionEnd: async (input, invocation) => {
2321
- console.log(`Session ended: ${input.reason}`);
2322
- },
2473
+ // Called when session starts
2474
+ onSessionStart: async (input, invocation) => {
2475
+ console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2476
+ return {
2477
+ additionalContext: "Session initialization context",
2478
+ };
2479
+ },
2323
2480
 
2324
- // Called when an error occurs
2325
- onErrorOccurred: async (input, invocation) => {
2326
- console.error(`Error in ${input.errorContext}: ${input.error}`);
2327
- return {
2328
- errorHandling: "retry", // "retry", "skip", or "abort"
2329
- };
2330
- },
2481
+ // Called when session ends
2482
+ onSessionEnd: async (input, invocation) => {
2483
+ console.log(`Session ended: ${input.reason}`);
2484
+ },
2331
2485
 
2332
- // Called when the top-level agent naturally stops
2333
- onAgentStop: async (input, invocation) => {
2334
- if (!input.stopHookActive && needsMoreWork()) {
2486
+ // Called when an error occurs
2487
+ onErrorOccurred: async (input, invocation) => {
2488
+ console.error(`Error in ${input.errorContext}: ${input.error}`);
2335
2489
  return {
2336
- decision: "block",
2337
- reason: "Run the final validation and fix any failures.",
2490
+ errorHandling: "retry", // "retry", "skip", or "abort"
2338
2491
  };
2339
- }
2340
- },
2492
+ },
2341
2493
 
2342
- // Called before a sub-agent's first turn (the input identifies the parent session)
2343
- onSubagentStart: (input, invocation) => {
2344
- console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2345
- return { additionalContext: "Check the requested file before reporting back." };
2346
- },
2494
+ // Called when the top-level agent naturally stops
2495
+ onAgentStop: async (input, invocation) => {
2496
+ if (!input.stopHookActive && needsMoreWork()) {
2497
+ return {
2498
+ decision: "block",
2499
+ reason: "Run the final validation and fix any failures.",
2500
+ };
2501
+ }
2502
+ },
2503
+
2504
+ // Called before a sub-agent's first turn (the input identifies the parent session)
2505
+ onSubagentStart: (input, invocation) => {
2506
+ console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2507
+ return { additionalContext: "Check the requested file before reporting back." };
2508
+ },
2347
2509
 
2348
- // Called when a sub-agent completes a turn
2349
- onSubagentStop: (input, invocation) => {
2350
- console.log(`${input.agentName} replied: ${input.response}`);
2351
- // Return { decision: "block", reason: "Continue checking the file." }
2352
- // to request another child turn instead.
2353
- return { modifiedResponse: `Reviewed: ${input.response}` };
2510
+ // Called when a sub-agent completes a turn
2511
+ onSubagentStop: (input, invocation) => {
2512
+ console.log(`${input.agentName} replied: ${input.response}`);
2513
+ // Return { decision: "block", reason: "Continue checking the file." }
2514
+ // to request another child turn instead.
2515
+ return { modifiedResponse: `Reviewed: ${input.response}` };
2516
+ },
2354
2517
  },
2355
2518
  },
2356
2519
  });
@@ -2362,87 +2525,89 @@ const session = await client.createSession({
2362
2525
  const session = await client.createSession({
2363
2526
  model: "gpt-5",
2364
2527
  hooks: {
2365
- // Called before each tool execution
2366
- onPreToolUse: async (input, invocation) => {
2367
- console.log(`About to run tool: ${input.toolName}`);
2368
- // Return permission decision and optionally modify args
2369
- return {
2370
- permissionDecision: "allow", // "allow", "deny", or "ask"
2371
- modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2372
- additionalContext: "Extra context for the model",
2373
- };
2374
- },
2375
-
2376
- // Called after each successful tool execution
2377
- onPostToolUse: async (input, invocation) => {
2378
- console.log(`Tool ${input.toolName} completed`);
2379
- // Optionally modify the result or add context
2380
- return {
2381
- additionalContext: "Post-execution notes",
2382
- };
2383
- },
2528
+ handlers: {
2529
+ // Called before each tool execution
2530
+ onPreToolUse: async (input, invocation) => {
2531
+ console.log(`About to run tool: ${input.toolName}`);
2532
+ // Return permission decision and optionally modify args
2533
+ return {
2534
+ permissionDecision: "allow", // "allow", "deny", or "ask"
2535
+ modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2536
+ additionalContext: "Extra context for the model",
2537
+ };
2538
+ },
2384
2539
 
2385
- // Called after a tool execution whose result was "failure".
2386
- // onPostToolUse does NOT fire for failed tool calls — register this
2387
- // hook to observe them. Input includes `error` (the failure message
2388
- // extracted from the tool's result), not the full result object.
2389
- onPostToolUseFailure: async (input, invocation) => {
2390
- console.log(`Tool ${input.toolName} failed: ${input.error}`);
2391
- // Optionally append hidden guidance to the model.
2392
- return { additionalContext: "Suggest checking inputs and retrying." };
2393
- },
2540
+ // Called after each successful tool execution
2541
+ onPostToolUse: async (input, invocation) => {
2542
+ console.log(`Tool ${input.toolName} completed`);
2543
+ // Optionally modify the result or add context
2544
+ return {
2545
+ additionalContext: "Post-execution notes",
2546
+ };
2547
+ },
2394
2548
 
2395
- // Called when user submits a prompt
2396
- onUserPromptSubmitted: async (input, invocation) => {
2397
- console.log(`User prompt: ${input.prompt}`);
2398
- return {
2399
- modifiedPrompt: input.prompt, // Optionally modify the prompt
2400
- };
2401
- },
2549
+ // Called after a tool execution whose result was "failure".
2550
+ // onPostToolUse does NOT fire for failed tool calls — register this
2551
+ // hook to observe them. Input includes `error` (the failure message
2552
+ // extracted from the tool's result), not the full result object.
2553
+ onPostToolUseFailure: async (input, invocation) => {
2554
+ console.log(`Tool ${input.toolName} failed: ${input.error}`);
2555
+ // Optionally append hidden guidance to the model.
2556
+ return { additionalContext: "Suggest checking inputs and retrying." };
2557
+ },
2402
2558
 
2403
- // Called when session starts
2404
- onSessionStart: async (input, invocation) => {
2405
- console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2406
- return {
2407
- additionalContext: "Session initialization context",
2408
- };
2409
- },
2559
+ // Called when user submits a prompt
2560
+ onUserPromptSubmitted: async (input, invocation) => {
2561
+ console.log(`User prompt: ${input.prompt}`);
2562
+ return {
2563
+ modifiedPrompt: input.prompt, // Optionally modify the prompt
2564
+ };
2565
+ },
2410
2566
 
2411
- // Called when session ends
2412
- onSessionEnd: async (input, invocation) => {
2413
- console.log(`Session ended: ${input.reason}`);
2414
- },
2567
+ // Called when session starts
2568
+ onSessionStart: async (input, invocation) => {
2569
+ console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2570
+ return {
2571
+ additionalContext: "Session initialization context",
2572
+ };
2573
+ },
2415
2574
 
2416
- // Called when an error occurs
2417
- onErrorOccurred: async (input, invocation) => {
2418
- console.error(`Error in ${input.errorContext}: ${input.error}`);
2419
- return {
2420
- errorHandling: "retry", // "retry", "skip", or "abort"
2421
- };
2422
- },
2575
+ // Called when session ends
2576
+ onSessionEnd: async (input, invocation) => {
2577
+ console.log(`Session ended: ${input.reason}`);
2578
+ },
2423
2579
 
2424
- // Called when the top-level agent naturally stops
2425
- onAgentStop: async (input, invocation) => {
2426
- if (!input.stopHookActive && needsMoreWork()) {
2580
+ // Called when an error occurs
2581
+ onErrorOccurred: async (input, invocation) => {
2582
+ console.error(`Error in ${input.errorContext}: ${input.error}`);
2427
2583
  return {
2428
- decision: "block",
2429
- reason: "Run the final validation and fix any failures.",
2584
+ errorHandling: "retry", // "retry", "skip", or "abort"
2430
2585
  };
2431
- }
2432
- },
2586
+ },
2433
2587
 
2434
- // Called before a sub-agent's first turn (the input identifies the parent session)
2435
- onSubagentStart: (input, invocation) => {
2436
- console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2437
- return { additionalContext: "Check the requested file before reporting back." };
2438
- },
2588
+ // Called when the top-level agent naturally stops
2589
+ onAgentStop: async (input, invocation) => {
2590
+ if (!input.stopHookActive && needsMoreWork()) {
2591
+ return {
2592
+ decision: "block",
2593
+ reason: "Run the final validation and fix any failures.",
2594
+ };
2595
+ }
2596
+ },
2597
+
2598
+ // Called before a sub-agent's first turn (the input identifies the parent session)
2599
+ onSubagentStart: (input, invocation) => {
2600
+ console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2601
+ return { additionalContext: "Check the requested file before reporting back." };
2602
+ },
2439
2603
 
2440
- // Called when a sub-agent completes a turn
2441
- onSubagentStop: (input, invocation) => {
2442
- console.log(`${input.agentName} replied: ${input.response}`);
2443
- // Return { decision: "block", reason: "Continue checking the file." }
2444
- // to request another child turn instead.
2445
- return { modifiedResponse: `Reviewed: ${input.response}` };
2604
+ // Called when a sub-agent completes a turn
2605
+ onSubagentStop: (input, invocation) => {
2606
+ console.log(`${input.agentName} replied: ${input.response}`);
2607
+ // Return { decision: "block", reason: "Continue checking the file." }
2608
+ // to request another child turn instead.
2609
+ return { modifiedResponse: `Reviewed: ${input.response}` };
2610
+ },
2446
2611
  },
2447
2612
  },
2448
2613
  });
@@ -2492,10 +2657,13 @@ npm test
2492
2657
  ### Internal feature-flag example
2493
2658
 
2494
2659
  [`examples/internal-feature-flags.ts`](examples/internal-feature-flags.ts) uses
2495
- the generated internal RPC factory against a real runtime over stdio.
2660
+ the generated RPC factories against a real runtime over stdio.
2496
2661
  It lists the catalog and shows environment, settings, and explicit-override
2497
2662
  precedence. It also checks that static resolution does not apply `COPILOT_EXP_*`
2498
- experiment assignments. It creates no session and sends no model request.
2663
+ experiment assignments. It then creates a session with a feature-flag
2664
+ configuration, checks that the session's `githubIqEnabled` setting predicate
2665
+ keeps its value after `options.update` changes `enabledFeatureFlags`, and
2666
+ destroys the session. It sends no model request.
2499
2667
 
2500
2668
  After you prepare matching runtime artifacts, run this from the runtime repository root:
2501
2669
 
@@ -2507,7 +2675,8 @@ COPILOT_RUNTIME_PROVIDER_LIB="$PWD/bazel-bin/src/native/runtime/runtime.node" \
2507
2675
  ```
2508
2676
 
2509
2677
  The JSON output includes `staticResolution` values of `false`, `true`, `false`,
2510
- and `true`, in that order. These methods are internal, not public SDK APIs.
2678
+ and `true`, in that order, and `lifecycleViaExistingMethods` of `[true, true]`.
2679
+ The feature-flag and settings-predicate methods are internal, not public SDK APIs.
2511
2680
 
2512
2681
  ## License
2513
2682