@microsoft/copilot-sdk 0.0.0-stage → 1.0.29-unstable.42916223485.gfff36db

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 (79) hide show
  1. package/README.md +2513 -2
  2. package/dist/canvas.d.ts +131 -0
  3. package/dist/canvas.js +50 -0
  4. package/dist/cjs/canvas.js +76 -0
  5. package/dist/cjs/cliVersion.js +31 -0
  6. package/dist/cjs/client.js +3754 -0
  7. package/dist/cjs/copilotRequestHandler.js +792 -0
  8. package/dist/cjs/decisions.js +139 -0
  9. package/dist/cjs/entra.js +83 -0
  10. package/dist/cjs/extension.js +76 -0
  11. package/dist/cjs/ffiRuntimeHost.js +400 -0
  12. package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
  13. package/dist/cjs/generated/rpc.js +5604 -0
  14. package/dist/cjs/generated/session-events.js +16 -0
  15. package/dist/cjs/host.js +83 -0
  16. package/dist/cjs/index.js +90 -0
  17. package/dist/cjs/installationConfirmation.js +98 -0
  18. package/dist/cjs/jsonrpcTypes.js +41 -0
  19. package/dist/cjs/package.json +1 -0
  20. package/dist/cjs/runtimeArtifacts.js +255 -0
  21. package/dist/cjs/schema.js +40 -0
  22. package/dist/cjs/sdkProtocolVersion.js +33 -0
  23. package/dist/cjs/session.js +2619 -0
  24. package/dist/cjs/sessionFsProvider.js +283 -0
  25. package/dist/cjs/telemetry.js +35 -0
  26. package/dist/cjs/toolSet.js +107 -0
  27. package/dist/cjs/types.js +193 -0
  28. package/dist/cjs/workflow.js +134 -0
  29. package/dist/cliVersion.d.ts +2 -0
  30. package/dist/cliVersion.js +6 -0
  31. package/dist/client.d.ts +557 -0
  32. package/dist/client.js +3737 -0
  33. package/dist/copilotRequestHandler.d.ts +91 -0
  34. package/dist/copilotRequestHandler.js +764 -0
  35. package/dist/decisions.d.ts +65 -0
  36. package/dist/decisions.js +113 -0
  37. package/dist/entra.d.ts +3 -0
  38. package/dist/entra.js +59 -0
  39. package/dist/extension.d.ts +59 -0
  40. package/dist/extension.js +56 -0
  41. package/dist/ffiRuntimeHost.d.ts +44 -0
  42. package/dist/ffiRuntimeHost.js +366 -0
  43. package/dist/generated/lifecycle-diagnostics.d.ts +224 -0
  44. package/dist/generated/lifecycle-diagnostics.js +0 -0
  45. package/dist/generated/rpc.d.ts +44538 -0
  46. package/dist/generated/rpc.js +5575 -0
  47. package/dist/generated/session-events.d.ts +17106 -0
  48. package/dist/generated/session-events.js +0 -0
  49. package/dist/host.d.ts +143 -0
  50. package/dist/host.js +59 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +62 -0
  53. package/dist/installationConfirmation.d.ts +19 -0
  54. package/dist/installationConfirmation.js +74 -0
  55. package/dist/jsonrpcTypes.d.ts +16 -0
  56. package/dist/jsonrpcTypes.js +17 -0
  57. package/dist/runtimeArtifacts.d.ts +18 -0
  58. package/dist/runtimeArtifacts.js +233 -0
  59. package/dist/schema.d.ts +4 -0
  60. package/dist/schema.js +14 -0
  61. package/dist/sdkProtocolVersion.d.ts +10 -0
  62. package/dist/sdkProtocolVersion.js +8 -0
  63. package/dist/session.d.ts +465 -0
  64. package/dist/session.js +2605 -0
  65. package/dist/sessionFsProvider.d.ts +130 -0
  66. package/dist/sessionFsProvider.js +257 -0
  67. package/dist/telemetry.d.ts +14 -0
  68. package/dist/telemetry.js +11 -0
  69. package/dist/toolSet.d.ts +75 -0
  70. package/dist/toolSet.js +82 -0
  71. package/dist/types.d.ts +3684 -0
  72. package/dist/types.js +159 -0
  73. package/dist/workflow.d.ts +367 -0
  74. package/dist/workflow.js +106 -0
  75. package/docs/agent-author.md +372 -0
  76. package/docs/examples.md +747 -0
  77. package/docs/extensions.md +82 -0
  78. package/docs/workflows.md +268 -0
  79. package/package.json +134 -5
package/README.md CHANGED
@@ -1,3 +1,2514 @@
1
- # Temporary Holding Version
1
+ # Copilot SDK for Node.js/TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK for programmatic control of GitHub Copilot CLI via JSON-RPC.
4
+
5
+ ## Prerequisites
6
+
7
+ To use the SDK, you'll need:
8
+
9
+ - Node.js ^20.19.0 or >=22.12.0
10
+
11
+ The SDK uses an optional `@microsoft/copilot-sdk-<platform>` package containing the
12
+ Copilot CLI runtime for the host platform. These packages contain the verified
13
+ runtime artifacts for that SDK release, so
14
+ starting the SDK performs no runtime download. Set `COPILOT_CLI_PATH` to use an
15
+ existing installation instead.
16
+
17
+ The checked-in `copilotCliVersion` in `package.json` and compiled metadata in
18
+ `src/cliVersion.ts` use a development placeholder. The public SDK snapshot
19
+ replaces both with the CLI version published for that snapshot.
20
+
21
+ `npm run pack:release` builds the main package and all platform packages. Set
22
+ `COPILOT_CLI_DOWNLOAD_BASE_URL` to use a release mirror while packaging.
23
+ Standalone source builds acquire stable/prerelease runtime assets from
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
26
+ downloads use that release location; mirror overrides retain the same tag scheme.
27
+ Release workflows instead set `COPILOT_SDK_RUNTIME_PACKAGE_DIR` to a directory
28
+ containing validated runtime npm package roots named for all eight platforms.
29
+ This keeps `COPILOT_CLI_USE_NPM_PACKAGE` false and embeds those runtime files in
30
+ the self-contained SDK platform packages.
31
+
32
+ In the runtime repository, packaging uses the prepared same-checkout runtime.
33
+ Set `COPILOT_SDK_RUNTIME_PLATFORMS` to the available target (for example,
34
+ `linux-x64`) for both `pack:release` and `verify:release-packages`. SDK CI checks
35
+ that target only; public release workflows leave this unset to package and
36
+ verify all eight platforms.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ npm install @microsoft/copilot-sdk
42
+ ```
43
+
44
+ ## Model provider metadata
45
+
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.
49
+ Native kinds remain `copilot` and `loki`; `id` is opaque and `label` is display text.
50
+ Configured BYOK and older, unattributed rows omit `provider`; do not infer Copilot
51
+ branding from a model ID or fill it from the active account. This metadata identifies
52
+ the model source, not the agent harness, an account, or a new routing/selection API.
53
+
54
+ ## Network callbacks (experimental)
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.
57
+
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.
60
+
61
+ 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
+ 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
+ ```ts
66
+ const client = new CopilotClient({ mode: "coding-agent",
67
+ network: {
68
+ scope: "runtime",
69
+ resolveProxy: async ({ url }) => session.resolveProxy(url),
70
+ authenticateNegotiate: async ({ spn }, signal) => acquireToken(spn, signal),
71
+ },
72
+ });
73
+ ```
74
+
75
+ ## Runtime-supervised AHP host (experimental)
76
+
77
+ `startAhpHost()` requires `authentication`: `github`, or direct-only `none` / `custom`
78
+ (`requireIdentity` and a validator returning `{identity,expiresAt}` or `null`):
79
+
80
+ <!-- docs-validate: strict -->
81
+ ```typescript
82
+ import { CopilotClient } from "@microsoft/copilot-sdk";
83
+
84
+ await using client = new CopilotClient({ mode: "coding-agent" });
85
+ await client.start();
86
+ const host = await client.startAhpHost({
87
+ localServer: {},
88
+ authentication: { mode: "github" },
89
+ onExit: (exit) => {
90
+ if (exit.error) console.error(exit.error);
91
+ },
92
+ });
93
+
94
+ // Connect an AHP client using host.url and host.token.
95
+ // Treat host.token as a secret; do not log it.
96
+
97
+ // Existing SDK sessions and AHP sessions share this runtime.
98
+ // Keep client alive while the listener is needed. Leaving this scope disposes
99
+ // client, and the runtime stops its listener without a separate host.dispose().
100
+ ```
101
+
102
+ The runtime hosts the complete AHP server in-process; the SDK does not launch a
103
+ second runtime or relay the host's traffic. The host has its own SDK connection
104
+ and belongs to the client connection that started it. Explicit disposal,
105
+ connection loss, and runtime shutdown stop the listener and its hosting task
106
+ without deleting underlying sessions. Reconnecting does not reclaim a host.
107
+ The optional `onExit` callback reports exits at most once. If the owner connection
108
+ is lost, it reports that loss rather than claiming that listener cleanup was
109
+ acknowledged.
110
+ Call `const { sessions } = await host.listSessions()` to read the complete catalog
111
+ of live and dormant sessions advertised by the host. The method returns a
112
+ `HostListSessionsResult` containing `sessions`, not a session array directly.
113
+
114
+ `host.pid` is absent for in-process listeners. The optional field is retained
115
+ for separate host process IDs returned by legacy runtimes, never the runtime PID.
116
+ Use `dispose()` to stop the listener. `reason: "exited"` reports hosting-task
117
+ failure, not runtime process death, and `exitCode` is absent. Hosting no longer
118
+ provides process isolation from the runtime.
119
+
120
+ Select at least one transport explicitly: `localServer: {}` enables the local
121
+ listener, `githubEnvironment: { name: "My app", computeId: "stable-installation-id" }`
122
+ registers a Mission Control environment and enables remote WPS connections, and
123
+ both enables both transports. GitHub-only hosting opens no local listener;
124
+ `host.url` and `host.token` are undefined, while `host.environmentId` identifies
125
+ the environment. The application supplies a stable compute ID and configures
126
+ transports only at startup. Dispose and recreate the host to change them.
127
+
128
+ The runtime validates options inside `localServer` and applies their defaults:
129
+
130
+ - `hostname` defaults to `127.0.0.1`. Set it explicitly to request a non-loopback
131
+ listener, such as `hostname: "0.0.0.0"`, and restrict network access appropriately.
132
+ - `port` defaults to `0`, which selects an available port.
133
+ - `requireConnectionToken` defaults to `true`. The runtime generates a random
134
+ token unless you supply a nonempty `token`.
135
+ - Set `requireConnectionToken: false` to disable token authentication;
136
+ `host.token` is then undefined. A supplied `token` cannot be combined with
137
+ `requireConnectionToken: false`.
138
+
139
+ The listener follows the owning client's lifetime. Call `await host.dispose()`
140
+ only when you want to stop it earlier; `await using host` also supports a shorter
141
+ scope. Each disposal call forwards to the runtime, which owns idempotent cleanup.
142
+ The AHP transport remains owned by the host.
143
+ Set top-level `computeId` to reuse the same durable catalog for local and Mission
144
+ Control hosting; it must agree with `githubEnvironment.computeId` when both are
145
+ supplied. Omitted local-only identities are persisted by the runtime, not generated
146
+ by the SDK. Published sessions remain discoverable after hosting stops.
147
+
148
+ ### Application-owned sessions
149
+
150
+ Supply `createSession` to materialize fresh AHP sessions in your application:
151
+
152
+ <!-- docs-validate: strict -->
153
+ ```typescript
154
+ import { approveAll, CopilotClient, defineTool } from "@microsoft/copilot-sdk";
155
+
156
+ await using client = new CopilotClient({ mode: "coding-agent" });
157
+ await using host = await client.startAhpHost({
158
+ localServer: {},
159
+ authentication: { mode: "github" },
160
+ createSession: ({ config, signal }) => {
161
+ signal.throwIfAborted();
162
+ return client.createSession({
163
+ ...config,
164
+ onPermissionRequest: approveAll,
165
+ 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
+ ],
173
+ });
174
+ },
175
+ onSessionReleased: async (originalSession) => {
176
+ // Optional: the app decides whether to disconnect, keep, or destroy it.
177
+ await originalSession.disconnect();
178
+ },
179
+ });
180
+ ```
181
+
182
+ Preserve the supplied `config`, including its fresh session identity, workspace,
183
+ and selected host settings. Add your prompt and tools where the host has not
184
+ explicitly selected those settings; conflicting settings fail rather than
185
+ silently advertising configuration that was not applied. Return a normal session
186
+ created by this same client. The creation factory does not adopt an arbitrary existing
187
+ session or expose unrelated application sessions in the AHP catalog.
188
+
189
+ Only the session ID returns through ordinary SDK RPC. The host attaches to **that same
190
+ resident session**, adding its own callback/tool registrations without replacing
191
+ the application's prompt, tool filters, hooks, or tools. Application tool functions
192
+ continue running in the app while their results stream through the existing AHP
193
+ projector. No second application connection or function serialization is involved.
194
+
195
+ The SDK retains the original returned object until participation ends and invokes
196
+ `onSessionReleased` at most once per handoff, including attach failure, hosting-task exit,
197
+ and owner disconnection. The SDK never automatically disconnects or destroys the
198
+ app object. The creation callback receives an abort signal; materialization
199
+ is bounded to 30 seconds and cancellation also releases objects returned late.
200
+ Graceful host disposal waits for AHP detach before reporting release. Omitting
201
+ `createSession` preserves copilotd-owned creation.
202
+
203
+ To restore durable application-owned sessions, also supply `resumeSession`.
204
+ It receives `{ sessionId, config, signal }` (`AhpSessionResumeRequest`).
205
+ Return the object from this client's `resumeSession(sessionId, { ...config,
206
+ onPermissionRequest, ... })`, restoring your tools, hooks, and handlers.
207
+ Alternatively, return a retained original session from this client when it
208
+ still matches the requested identity and workspace.
209
+ Only catalog entries marked as application-owned invoke this callback.
210
+ If the callback is missing, restoring such an entry fails instead of falling
211
+ back to host-owned creation.
212
+ Currently resident published sessions attach directly, without invoking it or replacing
213
+ their current registrations. Dormant published application sessions require this
214
+ resume callback to restore their tools and handlers. Resumed sessions follow the same original-object
215
+ retention, cancellation, late-result release, and `onSessionReleased` rules.
216
+
217
+ The `copilotd-hosting` library runs inside the runtime provider.
218
+ Development integrations require a
219
+ source-built launcher and provider (`COPILOT_RUNTIME_PROVIDER_LIB`). Older
220
+ runtimes without these RPC operations cannot start a host.
221
+
222
+ ## Run the Sample
223
+
224
+ Try the interactive chat sample (from the repo root):
225
+
226
+ ```bash
227
+ cd nodejs
228
+ npm ci
229
+ npm run build
230
+ export COPILOT_CLI_PATH="$(npm run --silent prepare:runtime -- --print-path)"
231
+ cd samples
232
+ npm install
233
+ npm start
234
+ ```
235
+
236
+ ## Quick Start
237
+
238
+ <!-- docs-validate: strict -->
239
+
240
+ ```typescript
241
+ import { CopilotClient, approveAll } from "@microsoft/copilot-sdk";
242
+
243
+ // Create and start client
244
+ const client = new CopilotClient({ mode: "coding-agent" });
245
+ await client.start();
246
+
247
+ // approveAll is only valid when managed settings are disabled.
248
+ const session = await client.createSession({
249
+ model: "gpt-5",
250
+ onPermissionRequest: approveAll,
251
+ });
252
+
253
+ // Wait for the response using typed event handlers
254
+ const done = new Promise<void>((resolve) => {
255
+ session.on("assistant.message", (event) => {
256
+ console.log(event.data.content);
257
+ });
258
+ session.on("session.idle", () => {
259
+ resolve();
260
+ });
261
+ });
262
+
263
+ // Send a message and wait for completion
264
+ await session.send({ prompt: "What is 2+2?" });
265
+ await done;
266
+
267
+ // Clean up
268
+ await session.disconnect();
269
+ await client.stop();
270
+ ```
271
+
272
+ Sessions also support `Symbol.asyncDispose` for use with [`await using`](https://github.com/tc39/proposal-explicit-resource-management) (TypeScript 5.2+ / Node.js 20+):
273
+
274
+ <!-- docs-validate: strict -->
275
+
276
+ ```typescript
277
+ import { approveAll } from "@microsoft/copilot-sdk";
278
+
279
+ await using session = await client.createSession({
280
+ model: "gpt-5",
281
+ onPermissionRequest: approveAll,
282
+ });
283
+ // session is automatically disconnected when leaving scope
284
+ ```
285
+
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
289
+ the raw `mcp:<server-key>-<tool-name>` form. For `customAgents[].tools` and
290
+ `defaultAgent.excludedTools`, use `<server-key>-<tool-name>` directly.
291
+
292
+ ## API Reference
293
+
294
+ ### CopilotClient
295
+
296
+ #### Constructor
297
+
298
+ ```typescript
299
+ new CopilotClient(options: CopilotClientOptions)
300
+ ```
301
+
302
+ **Options:**
303
+
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).
310
+ - 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
+ - `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`.
318
+
319
+ Set `COPILOT_TELEMETRY_DISABLED=true` before startup to disable Copilot-owned
320
+ GitHub and Entra authentication telemetry process-wide, including sessionless
321
+ events. Authentication, SDK `onGitHubTelemetry` forwarding, and user-configured
322
+ OpenTelemetry remain unchanged. The value must be exactly `"true"`; restart
323
+ the process to change it. With `RuntimeConnection.forInProcess()`, set the host
324
+ process environment; per-client `env` is rejected. `enableSessionTelemetry: false`
325
+ affects only the session pipeline. The existing native-runtime-only
326
+ `COPILOT_GITHUB_TELEMETRY_DISABLED=true` remains GitHub-only; the Node CLI host
327
+ uses the general variable or `--disable-client-telemetry` instead.
328
+
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.
334
+ - `sessionFs?: SessionFsConfig` - Custom session filesystem provider.
335
+
336
+ For a custom provider to serve images to the `view` tool, declare
337
+ `sessionFs.capabilities.binary: true` and implement
338
+ `readFileBytes(path): Promise<Uint8Array>` and
339
+ `writeFileBytes(path, content: Uint8Array, mode?: number): Promise<void>` on each session's provider. The
340
+ adapter transmits exact bytes as standard base64; text-only providers still
341
+ support text operations, but image reads fail rather than falling back to the
342
+ runtime machine's filesystem. A missing binary implementation is rejected
343
+ when a session is created.
344
+
345
+ Binary reads and writes are limited to 50,330,880 raw bytes (approximately 48 MiB);
346
+ larger results return a filesystem error before encoding or decoding.
347
+
348
+ - `sessionIdleTimeoutSeconds?: number` - Server-wide idle timeout for sessions in seconds. Ignored when connecting via `RuntimeConnection.forUri`.
349
+
350
+ #### Installation confirmation (experimental)
351
+
352
+ All six SDKs (Node.js, Python, Go, .NET, Java and Rust) provide this receiver with the
353
+ same semantics: each review gets one cancellation token, concurrent reviews are
354
+ independent, and a decision returned after cancellation is never sent. Without a
355
+ configured handler, an `installations.confirm` request is refused, which the
356
+ runtime treats as no consent.
357
+
358
+ The installation confirmation handler receives the generated
359
+ `InstallationConfirmationRequest` and a `CancellationToken`. Match `operationId`
360
+ and `policySessionId` against the exact original action on this connection
361
+ before presenting the complete review. Refuse unknown operations or incomplete
362
+ reviews; missing legacy session metadata is not permission to use the current
363
+ session. Return `"confirm"`, `"decline"` or `"cancel"` only after an explicit
364
+ human decision. The SDK echoes the original challenge and fingerprint.
365
+
366
+ Concurrent reviews remain independent. The token is cancelled when the runtime
367
+ retires the request, including runtime-enforced expiry, or when the original
368
+ connection closes. Observe it to close pending UI. Late handler results cannot
369
+ approve a retired request. This incoming signal does not cancel outbound
370
+ installation or OAuth RPCs, and dropping those promises is not cancellation.
371
+
372
+ Use `client.rpc.mcp.prepareInstall` before `applyInstall`: preparation returns an
373
+ inert runtime-issued `operationId` and original expiry. Register that ID with its
374
+ captured session on this exact client before applying. Removal uses
375
+ `planUninstall` then `applyUninstall`; the returned `operationId` identifies the
376
+ operation, while `planHandle` is the one-use removal input. Never interchange them.
377
+ Use `client.rpc.mcp.installations.list` and `recover` for owned inventory.
378
+ Inspect or cancel uncertain work through `status` and `cancel` on the original
379
+ connection and operation ID, without selecting a replacement session or replaying apply.
380
+
381
+ Owned OAuth similarly uses `session.rpc.mcp.oauth.prepareLogin` to obtain
382
+ `loginId` before browser, network or cached-reconnect work. Retain that ID with
383
+ the original session and `expectedInstallationId` for `login` and `cancelLogin`.
384
+ Prepare freezes reauthentication and display options. Cancelling an incoming
385
+ confirmation or abandoning a login promise is not a substitute for `cancelLogin`.
386
+ Manual MCP OAuth retains its direct `login` path.
387
+
388
+ A matching runtime contract and available owned-lifecycle support are required.
389
+ Capability negotiation does not promise availability; preserve typed refusals
390
+ instead of falling back to raw configuration writes. Generated presence and
391
+ transport tests do not establish a working installer, live OAuth or restart safety.
392
+
393
+ #### Methods
394
+
395
+ ##### `start(): Promise<void>`
396
+
397
+ Start the CLI server and establish connection.
398
+
399
+ ##### `stop(): Promise<Error[]>`
400
+
401
+ Stop the server and close all sessions. Returns a list of any errors encountered during cleanup.
402
+ For an owned stdio runtime, closes stdin and waits up to 10 seconds for host cleanup
403
+ (including telemetry export) and process exit before falling back to termination.
404
+ This graceful-exit timeout is separate from the shutdown RPC and post-termination wait.
405
+
406
+ ##### `forceStop(): Promise<void>`
407
+
408
+ Force stop the CLI server without graceful cleanup. Use when `stop()` takes too long.
409
+ Retained sessions are disconnected locally, and pending `sendAndWait()` calls reject
410
+ without waiting for `session.idle` or their response timeout.
411
+ Retirement releases session-owned tool, hook, auth/input, provider, workflow, canvas,
412
+ and transform registrations without changing caller-owned configuration. Late
413
+ registration and callback dispatch are rejected; callbacks already admitted may finish.
414
+
415
+ ##### `createSession(config: SessionConfig): Promise<CopilotSession>`
416
+
417
+ Create a new conversation session.
418
+
419
+ **Config:**
420
+
421
+ - `sessionId?: string` - Custom session ID.
422
+ - `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.
426
+ - `systemMessage?: SystemMessageConfig` - System message customization (see below)
427
+ - `infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
428
+ - `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).
443
+
444
+ <!-- docs-validate: strict -->
445
+ <!-- docs-validate: hidden -->
446
+ ```typescript
447
+ declare function acquireTokenForHost(host: string): Promise<string>;
448
+
449
+ const session = await client.createSession({
450
+ gitHubTokenProvider: async ({ host }) => ({
451
+ kind: "token",
452
+ accessToken: await acquireTokenForHost(host),
453
+ expiresIn: 8 * 60 * 60,
454
+ }),
455
+ });
456
+ ```
457
+ <!-- /docs-validate: hidden -->
458
+ ```typescript
459
+ const session = await client.createSession({
460
+ gitHubTokenProvider: async ({ host }) => ({
461
+ kind: "token",
462
+ accessToken: await acquireTokenForHost(host),
463
+ expiresIn: 8 * 60 * 60,
464
+ }),
465
+ });
466
+ ```
467
+
468
+ 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
+
470
+ ##### `resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>`
471
+
472
+ Both create and resume accept experimental `autopilot: AutopilotOptions`, and
473
+ `session.rpc.options.update({ autopilot: ... })` patches the same policy.
474
+ `continuationEnabled` controls runtime-owned continuation, not the session mode;
475
+ it defaults to `true`. `maxContinues` limits continuations outside an active
476
+ objective: a non-negative integer, default five, with zero allowing none.
477
+ Updates and warm resumes preserve
478
+ omitted fields; `{}` changes nothing. The policy is not persisted, so re-supply
479
+ it on cold resume. Pause state, prompt overrides, and no-progress detection are
480
+ internal runtime controls, not SDK options.
481
+
482
+ Resume an existing session. Returns the session with `workspacePath` populated if infinite sessions were enabled.
483
+ `allowTranscriptRecovery` controls whether the runtime may repair a damaged transcript during
484
+ resume. It defaults to `true` in all modes; set it to `false` to reject recovery.
485
+ When repair occurs, inspect `session.transcriptRecovery` for the planned backup path,
486
+ invalid line numbers, and whether `session.start` was moved. The backup
487
+ is written when the repaired transcript is next appended, not during resume. Disabling recovery
488
+ still permits adding a missing newline after an intact final record; it rejects torn tails.
489
+
490
+ ##### `ping(message?: string): Promise<{ message: string; timestamp: string }>`
491
+
492
+ Ping the server to check connectivity.
493
+
494
+ ##### `listSessions(filter?: SessionListFilter): Promise<SessionMetadata[]>`
495
+
496
+ List all available sessions. Optionally filter by working directory context.
497
+
498
+ **SessionMetadata:**
499
+
500
+ - `sessionId: string` - Unique session identifier
501
+ - `startTime: Date` - When the session was created
502
+ - `modifiedTime: Date` - When the session was last modified
503
+ - `summary?: string` - Optional session summary
504
+ - `isRemote: boolean` - Whether the session is remote
505
+ - `context?: SessionContext` - Working directory context from session creation
506
+ - `clientName?: string` - Client that created the session (for example `github/cli`)
507
+ - `lastClientName?: string` - Client that most recently ran the session: the client that created it, or a client that resumed it and then ran it. Resuming a session only to observe it does not change it. Omitted when unknown, such as for sessions persisted before this field existed.
508
+
509
+ **SessionContext:**
510
+
511
+ - `cwd: string` - Working directory where the session was created
512
+ - `gitRoot?: string` - Git repository root (if in a git repo)
513
+ - `repository?: string` - GitHub repository in "owner/repo" format
514
+ - `branch?: string` - Current git branch
515
+
516
+ ##### `deleteSession(sessionId: string): Promise<void>`
517
+
518
+ Delete a session and its data from disk.
519
+
520
+ ##### `getForegroundSessionId(): Promise<string | undefined>`
521
+
522
+ Get the ID of the session currently displayed in the TUI. Only available when connecting to a server running in TUI+server mode (`--ui-server`).
523
+
524
+ ##### `setForegroundSessionId(sessionId: string): Promise<void>`
525
+
526
+ Request the TUI to switch to displaying the specified session. Only available in TUI+server mode.
527
+
528
+ ##### `onLifecycle(eventType: SessionLifecycleEventType, handler): () => void`
529
+
530
+ Subscribe to a specific session lifecycle event type. Returns an unsubscribe function.
531
+
532
+ <!-- docs-validate: strict -->
533
+ ```typescript
534
+ const unsubscribe = client.onLifecycle("session.foreground", (event) => {
535
+ console.log(`Session ${event.sessionId} is now in foreground`);
536
+ });
537
+ ```
538
+
539
+ ##### `onLifecycle(handler: SessionLifecycleHandler): () => void`
540
+
541
+ Subscribe to all session lifecycle events. Returns an unsubscribe function.
542
+
543
+ <!-- docs-validate: strict -->
544
+ ```typescript
545
+ const unsubscribe = client.onLifecycle((event) => {
546
+ console.log(`${event.type}: ${event.sessionId}`);
547
+ });
548
+ ```
549
+
550
+ **Lifecycle Event Types:**
551
+
552
+ - `session.created` - A new session was created
553
+ - `session.deleted` - A session was deleted
554
+ - `session.updated` - A session was updated (e.g., new messages)
555
+ - `session.foreground` - A session became the foreground session in TUI
556
+ - `session.background` - A session is no longer the foreground session
557
+
558
+ ---
559
+
560
+ ### CopilotSession
561
+
562
+ Represents a single conversation session.
563
+
564
+ #### Properties
565
+
566
+ ##### `sessionId: string`
567
+
568
+ The unique identifier for this session.
569
+
570
+ ##### `workspacePath?: string`
571
+
572
+ Path to the session workspace directory when infinite sessions are enabled. Contains `checkpoints/`, `plan.md`, and `files/` subdirectories. Undefined if infinite sessions are disabled.
573
+
574
+ #### Methods
575
+
576
+ ##### `send(options: MessageOptions): Promise<string>`
577
+
578
+ Send a message to the session. Returns immediately after the message is queued; use event handlers or `sendAndWait()` to wait for completion.
579
+
580
+ **Options:**
581
+
582
+ - `prompt: string` - The message/prompt to send
583
+ - `source?: MessageSource` - `"user"`, `"system"`, or `` `agent-${string}` `` provenance; omitted by default
584
+ - `attachments?: Array<{type, path, displayName}>` - File attachments
585
+ - `mode?: "enqueue" | "immediate"` - Delivery mode
586
+ - `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))
587
+
588
+ Returns the message ID.
589
+
590
+ Use `source: "system"` for automated messages from your application:
591
+
592
+ <!-- docs-validate: strict -->
593
+ <!-- docs-validate: hidden -->
594
+ ```typescript
595
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
596
+
597
+ declare const session: CopilotSession;
598
+
599
+ await session.send({ prompt: "Context updated", source: "system" });
600
+ ```
601
+ <!-- /docs-validate: hidden -->
602
+ ```typescript
603
+ await session.send({ prompt: "Context updated", source: "system" });
604
+ ```
605
+
606
+ For a message from another agent, use its trusted sender ID:
607
+
608
+ <!-- docs-validate: strict -->
609
+ <!-- docs-validate: hidden -->
610
+ ```typescript
611
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
612
+
613
+ declare const session: CopilotSession;
614
+
615
+ await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
616
+ ```
617
+ <!-- /docs-validate: hidden -->
618
+ ```typescript
619
+ await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
620
+ ```
621
+
622
+ Source is independent of delivery mode. Leaving it unset preserves the existing human-message payload; it does not set billing flags or use the notification API.
623
+
624
+ ##### `sendAndWait(options: MessageOptions, timeout?: number): Promise<AssistantMessageEvent | undefined>`
625
+
626
+ Send a message and wait for its request-owned response completion.
627
+ Remote sessions retain the legacy non-Autopilot `session.idle` or correlated
628
+ `session.autopilot_stopped` wait. Autopilot completion does not wait for or stop
629
+ attached shells. Neither `assistant.idle` nor `session.task_complete` alone
630
+ completes the wait.
631
+ Sub-agent events are still delivered to listeners, but do not complete the wait or supply its reply.
632
+
633
+ **Options:**
634
+
635
+ - `prompt: string` - The message/prompt to send
636
+ - `source?: MessageSource` - Same optional provenance as `send`
637
+ - `attachments?: Array<{type, path, displayName}>` - File attachments
638
+ - `mode?: "enqueue" | "immediate"` - Delivery mode
639
+ - `clientTurnId?: string` - Same optional turn ID as `send`
640
+ - `timeout?: number` - Optional timeout in milliseconds
641
+
642
+ Returns the final assistant message event, or undefined if none was received.
643
+
644
+ ##### Structured output (preview)
645
+
646
+ Requires a runtime build with `responseFormat` and `originatingMessageId` support.
647
+ Pass a raw JSON Schema or a Zod schema as `responseSchema` to `send` or
648
+ `sendAndWait`. As with custom tool parameters, the SDK converts Zod schemas to
649
+ JSON Schema before sending them:
650
+
651
+ <!-- docs-validate: strict -->
652
+ <!-- docs-validate: hidden -->
653
+ ```typescript
654
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
655
+
656
+ declare const session: CopilotSession;
657
+
658
+ import { z } from "zod";
659
+
660
+ const answerSchema = z.object({ answer: z.number().int() });
661
+ const message = await session.sendAndWait({
662
+ prompt: "What is 19 + 23?",
663
+ responseSchema: answerSchema,
664
+ });
665
+ console.log(message?.data.content); // JSON text
666
+ ```
667
+ <!-- /docs-validate: hidden -->
668
+ ```typescript
669
+ import { z } from "zod";
670
+
671
+ const answerSchema = z.object({ answer: z.number().int() });
672
+ const message = await session.sendAndWait({
673
+ prompt: "What is 19 + 23?",
674
+ responseSchema: answerSchema,
675
+ });
676
+ console.log(message?.data.content); // JSON text
677
+ ```
678
+
679
+ For a typed result, pass the Zod schema as the **second argument** instead:
680
+
681
+ <!-- docs-validate: strict -->
682
+ <!-- docs-validate: hidden -->
683
+ ```typescript
684
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
685
+
686
+ declare const session: CopilotSession;
687
+ import { z } from "zod";
688
+
689
+ const answerSchema = z.object({ answer: z.number().int() });
690
+
691
+ const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
692
+ console.log(answer.answer); // number; TResult is inferred from answerSchema
693
+ ```
694
+ <!-- /docs-validate: hidden -->
695
+ ```typescript
696
+ const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
697
+ console.log(answer.answer); // number; TResult is inferred from answerSchema
698
+ ```
699
+
700
+ `sendAndWait<TResult>(options, schema, timeout?)` generates the JSON Schema from
701
+ the schema value, parses the final JSON, and validates it with the schema's
702
+ `parse` method. TypeScript cannot derive a runtime schema from an erased type
703
+ parameter alone. Invalid JSON, a schema mismatch, or a completed run without a
704
+ matching assistant message throws. Do not also set `options.responseSchema` when
705
+ using the typed overload.
706
+
707
+ The schema belongs to the submitted run, including its tool-call iterations.
708
+ Internally generated stop-hook corrections retain the schema and originating
709
+ message ID, so the wait returns the corrected answer. Independent subsequent
710
+ sends do not inherit it. Ordinary immediate steering inherits the active schema
711
+ and originating message ID, even when it arrives too late for the current model
712
+ request and is promoted into a follow-up run. Specifying a schema with
713
+ `mode: "immediate"` is rejected, even while idle.
714
+ Provider schema restrictions still apply, and schemas are not rewritten. Strict
715
+ OpenAI output needs an object root with every property listed in `required`.
716
+ Zod leaves `.optional()` properties out of `required`, so use `.nullable()` for a
717
+ field the model may leave empty.
718
+ The generated `session.rpc.send` and `session.rpc.sendMessages` wrappers expose
719
+ the full `responseFormat` contract when you need to set its name, description,
720
+ or strict option rather than using the convenience defaults (`name: "response"`,
721
+ `strict: true`).
722
+ Each batch starts one run: the final returned message ID is its origin, preceding
723
+ messages are context, and an empty batch has no origin. An immediate batch
724
+ steers the active run instead and retains its origin.
725
+ The schema is not a persisted session default: autonomous resume-pending work
726
+ after a restart does not restore it. A terminal tool that clears context ends
727
+ the old run; its fresh seed does not inherit the schema or origin. Such a run
728
+ can finish without a structured result, in which case the typed wait throws.
729
+ After a successful terminal tool, the runtime disables tools while the model
730
+ produces the structured result. Stop-hook corrections remain supported.
731
+ Remote sessions and known HydraFusion routes reject response formats before
732
+ admission. Schemas larger than 32 MiB when JSON-encoded are also rejected before
733
+ admission, using the runtime's existing request-size ceiling. This does not
734
+ guarantee the schema plus conversation and tools fits the provider's budget.
735
+
736
+ Structured and unformatted waits return their request's root-agent response when
737
+ its execution completes. Remote sessions retain event-based completion, selecting
738
+ the response and Autopilot terminal by originating request ID. Automatic
739
+ continuation messages do not change ownership. Child-agent events cannot supply
740
+ the result. Legacy errors without an ID cannot provide concurrent request-error
741
+ isolation.
742
+ `turnId` identifies an individual model/tool iteration, not the whole
743
+ run; telemetry interaction IDs are not unique run identifiers.
744
+
745
+ For event-driven consumption with `send`, subscribe before sending and collect
746
+ root `assistant.message` events whose `data.originatingMessageId` matches the ID
747
+ returned by `send`; events may arrive before that acknowledgement. Wait for
748
+ non-autopilot `session.idle`, or the matching `session.autopilot_stopped`, then
749
+ parse the last matching message without tool requests.
750
+ An earlier response may be superseded by a stop-hook correction. Handle
751
+ `session.error` and aborted idle events rather than returning a partial result.
752
+
753
+ Streaming still delivers ordinary text events, including intermediate messages
754
+ and tool calls. Only the final selected message is parsed by the typed overload;
755
+ not every event is necessarily a complete schema-conforming JSON document.
756
+ Provider errors, refusals, cancellation, truncation, session errors, and timeouts
757
+ can prevent a typed result. A timeout stops waiting, not the runtime's work.
758
+ Use a model and endpoint that support native structured output. An API-compatible
759
+ gateway may ignore format fields even when it accepts the request; for example,
760
+ the Claude Chat-completions compatibility route is not equivalent to Anthropic's
761
+ native `output_config.format` endpoint.
762
+
763
+ ##### `on(eventType: string, handler: TypedSessionEventHandler): () => void`
764
+
765
+ Subscribe to a specific event type. The handler receives properly typed events.
766
+
767
+ <!-- docs-validate: strict -->
768
+ <!-- docs-validate: hidden -->
769
+ ```typescript
770
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
771
+
772
+ declare const session: CopilotSession;
773
+
774
+ // Listen for specific event types with full type inference
775
+ session.on("assistant.message", (event) => {
776
+ console.log(event.data.content); // TypeScript knows about event.data.content
777
+ });
778
+
779
+ session.on("session.idle", () => {
780
+ console.log("Session is idle");
781
+ });
782
+
783
+ // Listen to streaming events
784
+ session.on("assistant.message_delta", (event) => {
785
+ process.stdout.write(event.data.deltaContent);
786
+ });
787
+ ```
788
+ <!-- /docs-validate: hidden -->
789
+ ```typescript
790
+ // Listen for specific event types with full type inference
791
+ session.on("assistant.message", (event) => {
792
+ console.log(event.data.content); // TypeScript knows about event.data.content
793
+ });
794
+
795
+ session.on("session.idle", () => {
796
+ console.log("Session is idle");
797
+ });
798
+
799
+ // Listen to streaming events
800
+ session.on("assistant.message_delta", (event) => {
801
+ process.stdout.write(event.data.deltaContent);
802
+ });
803
+ ```
804
+
805
+ ##### `on(handler: SessionEventHandler): () => void`
806
+
807
+ Subscribe to all session events. Returns an unsubscribe function.
808
+
809
+ <!-- docs-validate: strict -->
810
+ <!-- docs-validate: hidden -->
811
+ ```typescript
812
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
813
+
814
+ declare const session: CopilotSession;
815
+
816
+ const unsubscribe = session.on((event) => {
817
+ // Handle any event type
818
+ console.log(event.type, event);
819
+ });
820
+
821
+ // Later...
822
+ unsubscribe();
823
+ ```
824
+ <!-- /docs-validate: hidden -->
825
+ ```typescript
826
+ const unsubscribe = session.on((event) => {
827
+ // Handle any event type
828
+ console.log(event.type, event);
829
+ });
830
+
831
+ // Later...
832
+ unsubscribe();
833
+ ```
834
+
835
+ ##### `setModel(model: string, options?): Promise<void>`
836
+
837
+ Change the model for this session. The new model takes effect for the next message; conversation history is preserved.
838
+
839
+ **Options:**
840
+
841
+ - `reasoningEffort?: string` - Reasoning effort level
842
+ - `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.
843
+
844
+ ##### `setAutoTier(autoTier: AutoTier | null): Promise<ModelSwitchAutoTierResult>`
845
+
846
+ Change the Auto routing preference without changing the selected model. Pass `null` to return to the provider's default Auto routing.
847
+
848
+ The runtime does not apply the preference immediately. It records the request and commits it only when a later user turn using the `auto` model successfully obtains a usable model from the provider, so a `pending` status confirms acceptance rather than effect. Only the most recent request survives.
849
+
850
+ Watch for the outcome through the `session.model_change` event on success or the ephemeral `session.auto_tier_switch_failed` event on failure. A failed activation leaves the incumbent effective tier unchanged. Read the authoritative state at any time with `session.rpc.model.getCurrent()`.
851
+
852
+ <!-- docs-validate: strict -->
853
+ <!-- docs-validate: hidden -->
854
+ ```typescript
855
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
856
+
857
+ declare const session: CopilotSession;
858
+
859
+ const result = await session.setAutoTier("intelligence");
860
+ if (result.status === "pending") {
861
+ // Accepted, but not yet in effect.
862
+ }
863
+ ```
864
+ <!-- /docs-validate: hidden -->
865
+ ```typescript
866
+ const result = await session.setAutoTier("intelligence");
867
+ if (result.status === "pending") {
868
+ // Accepted, but not yet in effect.
869
+ }
870
+ ```
871
+
872
+ See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for the full lifecycle rules.
873
+
874
+ ##### `rpc.model.getReasoningSummaries(params)` (experimental)
875
+
876
+ 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
+
878
+ <!-- docs-validate: strict -->
879
+ <!-- docs-validate: hidden -->
880
+ ```typescript
881
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
882
+
883
+ declare const session: CopilotSession;
884
+
885
+ import type {
886
+ ModelGetReasoningSummariesRequest,
887
+ ModelGetReasoningSummariesResult,
888
+ } from "@microsoft/copilot-sdk";
889
+
890
+ const presentation: ModelGetReasoningSummariesRequest = { summariesVisible: false };
891
+ const policy: ModelGetReasoningSummariesResult =
892
+ await session.rpc.model.getReasoningSummaries(presentation);
893
+ ```
894
+ <!-- /docs-validate: hidden -->
895
+ ```typescript
896
+ import type {
897
+ ModelGetReasoningSummariesRequest,
898
+ ModelGetReasoningSummariesResult,
899
+ } from "@microsoft/copilot-sdk";
900
+
901
+ const presentation: ModelGetReasoningSummariesRequest = { summariesVisible: false };
902
+ const policy: ModelGetReasoningSummariesResult =
903
+ await session.rpc.model.getReasoningSummaries(presentation);
904
+ ```
905
+
906
+ Omit `persistedShowReasoning` when no visibility setting is saved. `visibility` can remain unset while experiment assignment is pending; `clearRedundantSetting` tells the host when its persisted setting matches the model default.
907
+
908
+ ##### `setTools(tools: Tool[]): Promise<void>`
909
+
910
+ Replace the tools this client supplies to the session, together with the handlers that serve them (experimental). `tools` takes the same definitions as `createSession` and becomes this client's complete tool set; pass `[]` to remove all of this client's tools. Built-in, MCP, and plugin tools, and tools other connected clients supply, are unaffected.
911
+
912
+ Once the runtime accepts the replacement, every tool call this session dispatches uses the new handlers; calls already running finish on their original handlers. If the runtime rejects it, the promise rejects and the previous tools and handlers stay in place. Concurrent calls are applied one at a time, in call order.
913
+
914
+ <!-- docs-validate: strict -->
915
+ <!-- docs-validate: hidden -->
916
+ ```typescript
917
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
918
+
919
+ declare const session: CopilotSession;
920
+ import { defineTool } from "@microsoft/copilot-sdk";
921
+ import { z } from "zod";
922
+
923
+ declare function searchIssues(query: string): Promise<string>;
924
+
925
+ await session.setTools([
926
+ defineTool("search_issues", {
927
+ description: "Search the issues shown on the current page",
928
+ parameters: z.object({ query: z.string() }),
929
+ handler: async ({ query }) => searchIssues(query),
930
+ }),
931
+ ]);
932
+ ```
933
+ <!-- /docs-validate: hidden -->
934
+ ```typescript
935
+ await session.setTools([
936
+ defineTool("search_issues", {
937
+ description: "Search the issues shown on the current page",
938
+ parameters: z.object({ query: z.string() }),
939
+ handler: async ({ query }) => searchIssues(query),
940
+ }),
941
+ ]);
942
+ ```
943
+
944
+ The agent sees the new tools from its next model request, which can fall within a turn in progress, so a model request already in flight can still call a tool you removed. See [Changing tools during a session](../docs/features/changing-tools.md) for the details.
945
+
946
+ ##### `abort(): Promise<void>`
947
+
948
+ Abort the currently processing message in this session.
949
+
950
+ ##### `getEvents(): Promise<SessionEvent[]>`
951
+
952
+ Get all events/messages from this session.
953
+
954
+ ##### `disconnect(): Promise<void>`
955
+
956
+ Disconnect the session and free resources. Session data on disk is preserved for later resumption.
957
+
958
+ ##### `capabilities: SessionCapabilities`
959
+
960
+ Host capabilities reported when the session was created or resumed. Use this to check feature support before calling capability-gated APIs.
961
+
962
+ <!-- docs-validate: strict -->
963
+ <!-- docs-validate: hidden -->
964
+ ```typescript
965
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
966
+
967
+ declare const session: CopilotSession;
968
+
969
+ if (session.capabilities.ui?.elicitation) {
970
+ const ok = await session.ui.confirm("Deploy?");
971
+ }
972
+ ```
973
+ <!-- /docs-validate: hidden -->
974
+ ```typescript
975
+ if (session.capabilities.ui?.elicitation) {
976
+ const ok = await session.ui.confirm("Deploy?");
977
+ }
978
+ ```
979
+
980
+ Capabilities may update during the session. For example, when another client joins or disconnects with an elicitation handler. The SDK automatically applies `capabilities.changed` events, so this property always reflects the current state.
981
+
982
+ ##### `ui: SessionUiApi`
983
+
984
+ Interactive UI methods for showing dialogs to the user. Only available when the CLI host supports elicitation (`session.capabilities.ui?.elicitation === true`). See [UI Elicitation](#ui-elicitation) for full details.
985
+
986
+ ---
987
+
988
+ ## Event Types
989
+
990
+ Sessions emit various events during processing:
991
+
992
+ - `user.message` - User message added
993
+ - `assistant.message` - Assistant response
994
+ - `assistant.message_delta` - Streaming response chunk
995
+ - `tool.execution_start` - Tool execution started
996
+ - `tool.execution_complete` - Tool execution completed
997
+ - `command.execute` - Command dispatch request (handled internally by the SDK)
998
+ - `commands.changed` - Command registration changed
999
+ - And more...
1000
+
1001
+ See `SessionEvent` type in the source for full details.
1002
+
1003
+ ## Image Support
1004
+
1005
+ The SDK supports image attachments via the `attachments` parameter. You can attach images by providing their file path, or by passing base64-encoded data directly using a blob attachment:
1006
+
1007
+ <!-- docs-validate: strict -->
1008
+ <!-- docs-validate: hidden -->
1009
+
1010
+ ```typescript
1011
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
1012
+
1013
+ declare const session: CopilotSession;
1014
+ declare const base64ImageData: string;
1015
+
1016
+ // File attachment — runtime reads from disk
1017
+ await session.send({
1018
+ prompt: "What's in this image?",
1019
+ attachments: [
1020
+ {
1021
+ type: "file",
1022
+ path: "/path/to/image.jpg",
1023
+ },
1024
+ ],
1025
+ });
1026
+
1027
+ // Blob attachment — provide base64 data directly
1028
+ await session.send({
1029
+ prompt: "What's in this image?",
1030
+ attachments: [
1031
+ {
1032
+ type: "blob",
1033
+ data: base64ImageData,
1034
+ mimeType: "image/png",
1035
+ },
1036
+ ],
1037
+ });
1038
+ ```
1039
+
1040
+ <!-- /docs-validate: hidden -->
1041
+
1042
+ ```typescript
1043
+ // File attachment — runtime reads from disk
1044
+ await session.send({
1045
+ prompt: "What's in this image?",
1046
+ attachments: [
1047
+ {
1048
+ type: "file",
1049
+ path: "/path/to/image.jpg",
1050
+ },
1051
+ ],
1052
+ });
1053
+
1054
+ // Blob attachment — provide base64 data directly
1055
+ await session.send({
1056
+ prompt: "What's in this image?",
1057
+ attachments: [
1058
+ {
1059
+ type: "blob",
1060
+ data: base64ImageData,
1061
+ mimeType: "image/png",
1062
+ },
1063
+ ],
1064
+ });
1065
+ ```
1066
+
1067
+ Supported image formats are PNG, JPEG, WebP, and GIF. Images in other formats, such as BMP or TIFF, are not sent to the model. The agent's `view` tool can also read images directly from the filesystem, so you can also ask questions like:
1068
+
1069
+ <!-- docs-validate: strict -->
1070
+ <!-- docs-validate: hidden -->
1071
+
1072
+ ```typescript
1073
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
1074
+
1075
+ declare const session: CopilotSession;
1076
+
1077
+ await session.send({ prompt: "What does the most recent jpg in this directory portray?" });
1078
+ ```
1079
+
1080
+ <!-- /docs-validate: hidden -->
1081
+
1082
+ ```typescript
1083
+ await session.send({ prompt: "What does the most recent jpg in this directory portray?" });
1084
+ ```
1085
+
1086
+ ## Streaming
1087
+
1088
+ Enable streaming to receive assistant response chunks as they're generated:
1089
+
1090
+ <!-- docs-validate: strict -->
1091
+ <!-- docs-validate: hidden -->
1092
+
1093
+ ```typescript
1094
+ import { approveAll } from "@microsoft/copilot-sdk";
1095
+
1096
+ const session = await client.createSession({
1097
+ 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,
1142
+ });
1143
+
1144
+ // Wait for completion using typed event handlers
1145
+ const done = new Promise<void>((resolve) => {
1146
+ session.on("assistant.message_delta", (event) => {
1147
+ // Streaming message chunk - print incrementally
1148
+ process.stdout.write(event.data.deltaContent);
1149
+ });
1150
+
1151
+ session.on("assistant.reasoning_delta", (event) => {
1152
+ // Streaming reasoning chunk (if model supports reasoning)
1153
+ process.stdout.write(event.data.deltaContent);
1154
+ });
1155
+
1156
+ session.on("assistant.message", (event) => {
1157
+ // Final message - complete content
1158
+ console.log("\n--- Final message ---");
1159
+ console.log(event.data.content);
1160
+ });
1161
+
1162
+ session.on("assistant.reasoning", (event) => {
1163
+ // Final reasoning content (if model supports reasoning)
1164
+ console.log("--- Reasoning ---");
1165
+ console.log(event.data.content);
1166
+ });
1167
+
1168
+ session.on("session.idle", () => {
1169
+ // Session finished processing
1170
+ resolve();
1171
+ });
1172
+ });
1173
+
1174
+ await session.send({ prompt: "Tell me a short story" });
1175
+ await done; // Wait for streaming to complete
1176
+ ```
1177
+
1178
+ When `streaming: true`:
1179
+
1180
+ - `assistant.message_delta` events are sent with `deltaContent` containing incremental text
1181
+ - `assistant.reasoning_delta` events are sent with `deltaContent` for reasoning/chain-of-thought (model-dependent)
1182
+ - Accumulate `deltaContent` values to build the full response progressively
1183
+ - The final `assistant.message` and `assistant.reasoning` events contain the complete content
1184
+
1185
+ Note: `assistant.message` and `assistant.reasoning` (final events) are always sent regardless of streaming setting.
1186
+
1187
+ ## Advanced Usage
1188
+
1189
+ ### Manual Server Control
1190
+
1191
+ <!-- docs-validate: strict -->
1192
+
1193
+ ```typescript
1194
+ import { CopilotClient } from "@microsoft/copilot-sdk";
1195
+
1196
+ const client = new CopilotClient({ mode: "coding-agent"});
1197
+
1198
+ // Start manually
1199
+ await client.start();
1200
+
1201
+ // Use client...
1202
+
1203
+ // Stop manually
1204
+ await client.stop();
1205
+ ```
1206
+
1207
+ ### Tools
1208
+
1209
+ You can let the CLI call back into your process when the model needs capabilities you own. Use `defineTool` with Zod schemas for type-safe tool definitions:
1210
+
1211
+ <!-- docs-validate: strict -->
1212
+ <!-- docs-validate: hidden -->
1213
+
1214
+ ```ts
1215
+ import { z } from "zod";
1216
+ import { defineTool } from "@microsoft/copilot-sdk";
1217
+
1218
+ declare function fetchIssue(id: string): Promise<string>;
1219
+
1220
+ const session = await client.createSession({
1221
+ 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"),
1227
+ }),
1228
+ handler: async ({ id }) => {
1229
+ const issue = await fetchIssue(id);
1230
+ return issue;
1231
+ },
1232
+ }),
1233
+ ],
1234
+ });
1235
+ ```
1236
+
1237
+ <!-- /docs-validate: hidden -->
1238
+
1239
+ ```ts
1240
+ import { z } from "zod";
1241
+ import { CopilotClient, defineTool } from "@microsoft/copilot-sdk";
1242
+
1243
+ const session = await client.createSession({
1244
+ 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"),
1250
+ }),
1251
+ handler: async ({ id }) => {
1252
+ const issue = await fetchIssue(id);
1253
+ return issue;
1254
+ },
1255
+ }),
1256
+ ],
1257
+ });
1258
+ ```
1259
+
1260
+ When Copilot invokes `lookup_issue`, the client automatically runs your handler and responds to the CLI. Handlers can return any JSON-serializable value (automatically wrapped), a simple string, or a `ToolResultObject` for full control over result metadata. Raw JSON schemas are also supported if Zod isn't desired.
1261
+
1262
+ #### Overriding Built-in Tools
1263
+
1264
+ If you register a tool with the same name as a built-in CLI tool (e.g. `edit_file`, `read_file`), the SDK will throw an error unless you explicitly opt in by setting `overridesBuiltInTool: true`. This flag signals that you intend to replace the built-in tool with your custom implementation.
1265
+
1266
+ <!-- docs-validate: strict -->
1267
+ <!-- docs-validate: hidden -->
1268
+
1269
+ ```ts
1270
+ import { z } from "zod";
1271
+ import { defineTool } from "@microsoft/copilot-sdk";
1272
+
1273
+ defineTool("edit_file", {
1274
+ description: "Custom file editor with project-specific validation",
1275
+ parameters: z.object({ path: z.string(), content: z.string() }),
1276
+ overridesBuiltInTool: true,
1277
+ handler: async ({ path, content }) => {
1278
+ /* your logic */
1279
+ },
1280
+ });
1281
+ ```
1282
+
1283
+ <!-- /docs-validate: hidden -->
1284
+
1285
+ ```ts
1286
+ defineTool("edit_file", {
1287
+ description: "Custom file editor with project-specific validation",
1288
+ parameters: z.object({ path: z.string(), content: z.string() }),
1289
+ overridesBuiltInTool: true,
1290
+ handler: async ({ path, content }) => {
1291
+ /* your logic */
1292
+ },
1293
+ });
1294
+ ```
1295
+
1296
+ An `apply_patch` override can declare a string schema. The model sees a required
1297
+ `input` property, but the runtime restores the declared scalar shape before
1298
+ dispatching to any SDK. Both a Zod-inferred Node handler and
1299
+ `invocation.arguments` receive the patch text as a string:
1300
+
1301
+ <!-- docs-validate: strict -->
1302
+ <!-- docs-validate: hidden -->
1303
+
1304
+ ```ts
1305
+ import { z } from "zod";
1306
+ import { defineTool } from "@microsoft/copilot-sdk";
1307
+
1308
+ defineTool("apply_patch", {
1309
+ parameters: z.string(),
1310
+ overridesBuiltInTool: true,
1311
+ handler: (patch) => patch.trim(),
1312
+ });
1313
+ ```
1314
+
1315
+ <!-- /docs-validate: hidden -->
1316
+
1317
+ ```ts
1318
+ defineTool("apply_patch", {
1319
+ parameters: z.string(),
1320
+ overridesBuiltInTool: true,
1321
+ handler: (patch) => patch.trim(),
1322
+ });
1323
+ ```
1324
+
1325
+ String-schema `apply_patch` overrides cannot contain JSON Schema references;
1326
+ use an object schema if references are needed.
1327
+
1328
+ #### Skipping Permission Prompts
1329
+
1330
+ Set `skipPermission: true` on a tool definition to allow it to execute without triggering a permission prompt:
1331
+
1332
+ <!-- docs-validate: strict -->
1333
+ <!-- docs-validate: hidden -->
1334
+
1335
+ ```ts
1336
+ import { z } from "zod";
1337
+ import { defineTool } from "@microsoft/copilot-sdk";
1338
+
1339
+ defineTool("safe_lookup", {
1340
+ description: "A read-only lookup that needs no confirmation",
1341
+ parameters: z.object({ id: z.string() }),
1342
+ skipPermission: true,
1343
+ handler: async ({ id }) => {
1344
+ /* your logic */
1345
+ },
1346
+ });
1347
+ ```
1348
+
1349
+ <!-- /docs-validate: hidden -->
1350
+
1351
+ ```ts
1352
+ defineTool("safe_lookup", {
1353
+ description: "A read-only lookup that needs no confirmation",
1354
+ parameters: z.object({ id: z.string() }),
1355
+ skipPermission: true,
1356
+ handler: async ({ id }) => {
1357
+ /* your logic */
1358
+ },
1359
+ });
1360
+ ```
1361
+
1362
+ #### Deferring Tools
1363
+
1364
+ Set `defer` to control whether a tool may be loaded lazily via tool search rather than always pre-loaded. Use `"auto"` to allow the tool to be deferred and surfaced through tool search, or `"never"` to force it to always be pre-loaded. Defaults to `"auto"`.
1365
+
1366
+ <!-- docs-validate: strict -->
1367
+ <!-- docs-validate: hidden -->
1368
+
1369
+ ```ts
1370
+ import { z } from "zod";
1371
+ import { defineTool } from "@microsoft/copilot-sdk";
1372
+
1373
+ defineTool("lookup_issue", {
1374
+ description: "Fetch issue details",
1375
+ parameters: z.object({ id: z.string() }),
1376
+ defer: "auto",
1377
+ handler: async ({ id }) => {
1378
+ /* your logic */
1379
+ },
1380
+ });
1381
+ ```
1382
+
1383
+ <!-- /docs-validate: hidden -->
1384
+
1385
+ ```ts
1386
+ defineTool("lookup_issue", {
1387
+ description: "Fetch issue details",
1388
+ parameters: z.object({ id: z.string() }),
1389
+ defer: "auto",
1390
+ handler: async ({ id }) => {
1391
+ /* your logic */
1392
+ },
1393
+ });
1394
+ ```
1395
+
1396
+ ### Commands
1397
+
1398
+ Register slash commands so that users of the CLI's TUI can invoke custom actions via `/commandName`. Each command has a `name`, optional `description`, and a `handler` called when the user executes it.
1399
+
1400
+ <!-- docs-validate: strict -->
1401
+ <!-- docs-validate: hidden -->
1402
+
1403
+ ```ts
1404
+ import { approveAll } from "@microsoft/copilot-sdk";
1405
+
1406
+ 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
1415
+ },
1416
+ },
1417
+ ],
1418
+ });
1419
+ ```
1420
+
1421
+ <!-- /docs-validate: hidden -->
1422
+
1423
+ ```ts
1424
+ 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
1433
+ },
1434
+ },
1435
+ ],
1436
+ });
1437
+ ```
1438
+
1439
+ When the user types `/deploy staging` in the CLI, the SDK receives a `command.execute` event, routes it to your handler, and automatically responds to the CLI. If the handler throws, the error message is forwarded.
1440
+
1441
+ Commands are sent to the CLI on both `createSession` and `resumeSession`, so you can update the command set when resuming.
1442
+
1443
+ ### UI Elicitation
1444
+
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.
1446
+
1447
+ > **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
+
1449
+ <!-- docs-validate: strict -->
1450
+ <!-- docs-validate: hidden -->
1451
+
1452
+ ```ts
1453
+ import { approveAll } from "@microsoft/copilot-sdk";
1454
+
1455
+ const session = await client.createSession({ onPermissionRequest: approveAll });
1456
+
1457
+ if (session.capabilities.ui?.elicitation) {
1458
+ // Confirm dialog — returns boolean
1459
+ const ok = await session.ui.confirm("Deploy to production?");
1460
+
1461
+ // Selection dialog — returns selected value or null
1462
+ const env = await session.ui.select("Pick environment", ["production", "staging", "dev"]);
1463
+
1464
+ // Text input — returns string or null
1465
+ const name = await session.ui.input("Project name:", {
1466
+ title: "Name",
1467
+ minLength: 1,
1468
+ maxLength: 50,
1469
+ });
1470
+
1471
+ // Generic elicitation with full schema control
1472
+ const result = await session.ui.elicitation({
1473
+ message: "Configure deployment",
1474
+ requestedSchema: {
1475
+ type: "object",
1476
+ properties: {
1477
+ region: { type: "string", enum: ["us-east", "eu-west"] },
1478
+ dryRun: { type: "boolean", default: true },
1479
+ },
1480
+ required: ["region"],
1481
+ },
1482
+ });
1483
+ // result.action: "accept" | "decline" | "cancel"
1484
+ // result.content: { region: "us-east", dryRun: true } (when accepted)
1485
+ }
1486
+ ```
1487
+
1488
+ <!-- /docs-validate: hidden -->
1489
+
1490
+ ```ts
1491
+ const session = await client.createSession({ onPermissionRequest: approveAll });
1492
+
1493
+ if (session.capabilities.ui?.elicitation) {
1494
+ // Confirm dialog — returns boolean
1495
+ const ok = await session.ui.confirm("Deploy to production?");
1496
+
1497
+ // Selection dialog — returns selected value or null
1498
+ const env = await session.ui.select("Pick environment", ["production", "staging", "dev"]);
1499
+
1500
+ // Text input — returns string or null
1501
+ const name = await session.ui.input("Project name:", {
1502
+ title: "Name",
1503
+ minLength: 1,
1504
+ maxLength: 50,
1505
+ });
1506
+
1507
+ // Generic elicitation with full schema control
1508
+ const result = await session.ui.elicitation({
1509
+ message: "Configure deployment",
1510
+ requestedSchema: {
1511
+ type: "object",
1512
+ properties: {
1513
+ region: { type: "string", enum: ["us-east", "eu-west"] },
1514
+ dryRun: { type: "boolean", default: true },
1515
+ },
1516
+ required: ["region"],
1517
+ },
1518
+ });
1519
+ // result.action: "accept" | "decline" | "cancel"
1520
+ // result.content: { region: "us-east", dryRun: true } (when accepted)
1521
+ }
1522
+ ```
1523
+
1524
+ All UI methods throw if elicitation is not supported by the host.
1525
+
1526
+ ### System Message Customization
1527
+
1528
+ Control the system prompt using `systemMessage` in session config:
1529
+
1530
+ <!-- docs-validate: strict -->
1531
+
1532
+ ```typescript
1533
+ const session = await client.createSession({
1534
+ model: "gpt-5",
1535
+ systemMessage: {
1536
+ content: `
1537
+ <workflow_rules>
1538
+ - Always check for security vulnerabilities
1539
+ - Suggest performance improvements when applicable
1540
+ </workflow_rules>
1541
+ `,
1542
+ },
1543
+ });
1544
+ ```
1545
+
1546
+ The SDK auto-injects environment context, tool instructions, and security guardrails. The default CLI persona is preserved, and your `content` is appended after SDK-managed sections. To change the persona or fully redefine the prompt, use `mode: "replace"` or `mode: "customize"`.
1547
+
1548
+ #### Customize Mode
1549
+
1550
+ Use `mode: "customize"` to selectively override individual sections of the prompt while preserving the rest:
1551
+
1552
+ <!-- docs-validate: strict -->
1553
+
1554
+ ```typescript
1555
+ import { SYSTEM_MESSAGE_SECTIONS } from "@microsoft/copilot-sdk";
1556
+ import type { SectionOverride, SystemMessageSection } from "@microsoft/copilot-sdk";
1557
+
1558
+ const session = await client.createSession({
1559
+ model: "gpt-5",
1560
+ systemMessage: {
1561
+ mode: "customize",
1562
+ sections: {
1563
+ // Replace the tone/style section
1564
+ tone: {
1565
+ action: "replace",
1566
+ content: "Respond in a warm, professional tone. Be thorough in explanations.",
1567
+ },
1568
+ // Remove coding-specific rules
1569
+ code_change_rules: { action: "remove" },
1570
+ // Append to existing guidelines
1571
+ guidelines: { action: "append", content: "\n* Always cite data sources" },
1572
+ },
1573
+ // Additional instructions appended after all sections
1574
+ content: "Focus on financial analysis and reporting.",
1575
+ },
1576
+ });
1577
+ ```
1578
+
1579
+ Available section IDs: `preamble`, `identity`, `tone`, `tool_efficiency`, `environment_context`, `code_change_rules`, `guidelines`, `safety`, `tool_instructions`, `custom_instructions`, `runtime_instructions`, `last_instructions`. Use the `SYSTEM_MESSAGE_SECTIONS` constant for descriptions of each section.
1580
+
1581
+ `identity` and `tool_instructions` are section _groups_ that target a collection of related sub-sections as a unit. Use `preamble` to target just the identity preamble without affecting its sibling sub-sections.
1582
+
1583
+ `last_instructions` includes configured subagent-model guidance when the `task` tool is available. Removing or replacing this section also removes that guidance; a transform callback receives the complete section, including the guidance, and its returned content is authoritative. Append, prepend, and preserve retain their usual section semantics. These overrides change prompt prose only, not configured subagent models, tool availability, or runtime dispatch policy. `runtime_instructions` is a separate section: removing it does not remove `last_instructions`.
1584
+
1585
+ Each section override supports five actions:
1586
+
1587
+ - **`replace`** — Replace the section content entirely
1588
+ - **`remove`** — Remove the section from the prompt
1589
+ - **`append`** — Add content after the existing section
1590
+ - **`prepend`** — Add content before the existing section
1591
+ - **`preserve`** — No-op that opts an individually-addressable section out of a group-level `remove`
1592
+
1593
+ An `action` can also be a callback that receives the current section content and returns the replacement content, synchronously or asynchronously.
1594
+
1595
+ Unknown section IDs are handled gracefully: content from `replace`/`append`/`prepend` overrides is appended to additional instructions, and `remove` overrides are silently ignored.
1596
+
1597
+ #### Replace Mode
1598
+
1599
+ For full control (removes all guardrails), use `mode: "replace"`:
1600
+
1601
+ <!-- docs-validate: strict -->
1602
+
1603
+ ```typescript
1604
+ const session = await client.createSession({
1605
+ model: "gpt-5",
1606
+ systemMessage: {
1607
+ mode: "replace",
1608
+ content: "You are a helpful assistant.",
1609
+ },
1610
+ });
1611
+ ```
1612
+
1613
+ ### Infinite Sessions
1614
+
1615
+ By default, sessions use **infinite sessions** which automatically manage context window limits through background compaction and persist state to a workspace directory.
1616
+
1617
+ <!-- docs-validate: strict -->
1618
+ <!-- docs-validate: hidden -->
1619
+
1620
+ ```typescript
1621
+ // Default: infinite sessions enabled with default thresholds
1622
+ const session = await client.createSession({ model: "gpt-5" });
1623
+
1624
+ // Access the workspace path for checkpoints and files
1625
+ console.log(session.workspacePath);
1626
+ // => ~/.copilot/session-state/{sessionId}/
1627
+
1628
+ // Custom thresholds
1629
+ const tuned = await client.createSession({
1630
+ 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
1635
+ },
1636
+ });
1637
+
1638
+ // Disable infinite sessions
1639
+ const disabled = await client.createSession({
1640
+ model: "gpt-5",
1641
+ infiniteSessions: { enabled: false },
1642
+ });
1643
+ ```
1644
+
1645
+ <!-- /docs-validate: hidden -->
1646
+
1647
+ ```typescript
1648
+ // Default: infinite sessions enabled with default thresholds
1649
+ const session = await client.createSession({ model: "gpt-5" });
1650
+
1651
+ // Access the workspace path for checkpoints and files
1652
+ console.log(session.workspacePath);
1653
+ // => ~/.copilot/session-state/{sessionId}/
1654
+
1655
+ // Custom thresholds
1656
+ const tuned = await client.createSession({
1657
+ 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
1662
+ },
1663
+ });
1664
+
1665
+ // Disable infinite sessions
1666
+ const disabled = await client.createSession({
1667
+ model: "gpt-5",
1668
+ infiniteSessions: { enabled: false },
1669
+ });
1670
+ ```
1671
+
1672
+ When enabled, sessions emit compaction events:
1673
+
1674
+ - `session.compaction_start` - Background compaction started
1675
+ - `session.compaction_complete` - Compaction finished (includes token counts)
1676
+
1677
+ ### Memory
1678
+
1679
+ Sessions can opt in to the memory feature, which lets the agent persist and recall
1680
+ information across turns. Provide a `memory` configuration on session create or resume;
1681
+ when omitted, the runtime default applies. In `"coding-agent"` client mode the
1682
+ SDK leaves `memory` unset so the runtime applies its own default, while `"empty"` mode
1683
+ defaults `memory` to disabled unless you set it explicitly.
1684
+ For more background, see [About GitHub Copilot Memory](https://docs.github.com/en/copilot/concepts/agents/copilot-memory).
1685
+
1686
+ <!-- docs-validate: strict -->
1687
+ <!-- docs-validate: hidden -->
1688
+
1689
+ ```typescript
1690
+ // Enable memory for a session
1691
+ const enabled = await client.createSession({
1692
+ model: "gpt-5",
1693
+ memory: { enabled: true },
1694
+ });
1695
+
1696
+ // Disable memory for a session
1697
+ const disabled = await client.createSession({
1698
+ model: "gpt-5",
1699
+ memory: { enabled: false },
1700
+ });
1701
+ ```
1702
+
1703
+ <!-- /docs-validate: hidden -->
1704
+
1705
+ ```typescript
1706
+ // Enable memory for a session
1707
+ const enabled = await client.createSession({
1708
+ model: "gpt-5",
1709
+ memory: { enabled: true },
1710
+ });
1711
+
1712
+ // Disable memory for a session
1713
+ const disabled = await client.createSession({
1714
+ model: "gpt-5",
1715
+ memory: { enabled: false },
1716
+ });
1717
+ ```
1718
+
1719
+ ### Skill providers (experimental)
1720
+
1721
+ A skill provider serves skills from your own storage, such as a database, instead of `SKILL.md`
1722
+ files on disk. Provider skills join the session's skill catalog and load on demand through the
1723
+ `skill` tool, just like file-based skills.
1724
+
1725
+ <!-- docs-validate: strict -->
1726
+ <!-- docs-validate: hidden -->
1727
+
1728
+ ```typescript
1729
+ import { approveAll } from "@microsoft/copilot-sdk";
1730
+ import type { SkillProvider } from "@microsoft/copilot-sdk";
1731
+
1732
+ declare const db: {
1733
+ findSkill(
1734
+ name: string,
1735
+ options: { signal: AbortSignal }
1736
+ ): Promise<{ markdown: string } | undefined>;
1737
+ };
1738
+
1739
+ const skillProvider: SkillProvider = {
1740
+ listSkills: async () => [
1741
+ { name: "release-notes", description: "Writes release notes in the team's format." },
1742
+ ],
1743
+ readSkill: async (name, { signal }) => (await db.findSkill(name, { signal }))?.markdown ?? null,
1744
+ };
1745
+
1746
+ const session = await client.createSession({
1747
+ onPermissionRequest: approveAll,
1748
+ skillProvider,
1749
+ });
1750
+ ```
1751
+
1752
+ <!-- /docs-validate: hidden -->
1753
+
1754
+ ```typescript
1755
+ import type { SkillProvider } from "@microsoft/copilot-sdk";
1756
+
1757
+ const skillProvider: SkillProvider = {
1758
+ listSkills: async () => [
1759
+ { name: "release-notes", description: "Writes release notes in the team's format." },
1760
+ ],
1761
+ readSkill: async (name, { signal }) => (await db.findSkill(name, { signal }))?.markdown ?? null,
1762
+ };
1763
+
1764
+ const session = await client.createSession({
1765
+ onPermissionRequest: approveAll,
1766
+ skillProvider,
1767
+ });
1768
+ ```
1769
+
1770
+ - `listSkills()` returns the catalog metadata. `readSkill(name)` returns the skill's markdown, or
1771
+ `null`/`undefined` if the skill no longer exists. The markdown may omit YAML frontmatter; when
1772
+ frontmatter is present, its fields must agree with the listed metadata, and `allowed-tools` is
1773
+ read only from frontmatter.
1774
+ - Each call receives `{ signal }`, an `AbortSignal` that fires when the runtime cancels the call,
1775
+ for example after its 30-second limit or when the session disconnects. It doesn't fire when the
1776
+ connection closes or the client is force-stopped; a running call then continues until it returns.
1777
+ - The provider is never persisted. Pass it again to `resumeSession`; resuming without it unbinds
1778
+ the provider.
1779
+ - A provider enables skills unless you set `enableSkills: false`, which keeps it bound but unused.
1780
+ In `mode: "empty"`, skills stay disabled until you set `enableSkills: true`.
1781
+ - Errors thrown by the provider are reported to the model as a generic load failure; their
1782
+ messages are not forwarded.
1783
+ - The runtime may call the provider concurrently, so both methods must be safe for concurrent use.
1784
+ - Skill providers are not supported for cloud sessions.
1785
+
1786
+ See [Custom skills](../docs/features/skills.md#skill-providers-experimental) for limits and details.
1787
+
1788
+ #### Supporting files (experimental)
1789
+
1790
+ To give a provider skill supporting files, such as scripts, references,
1791
+ templates, and assets, set its descriptor's `directory` to the absolute path of
1792
+ the folder that holds them:
1793
+
1794
+ ```typescript
1795
+ {
1796
+ name: "release-notes",
1797
+ description: "Writes release notes in the team's format.",
1798
+ directory: "/srv/skills/release-notes",
1799
+ }
1800
+ ```
1801
+
1802
+ When the skill is activated, the runtime lists the folder's files for the model.
1803
+ See [Supporting files](../docs/features/skills.md#supporting-files-experimental) for details.
1804
+
1805
+ ### Multiple Sessions
1806
+
1807
+ <!-- docs-validate: strict -->
1808
+
1809
+ ```typescript
1810
+ const session1 = await client.createSession({ model: "gpt-5" });
1811
+ const session2 = await client.createSession({ model: "claude-sonnet-4.5" });
1812
+
1813
+ // Both sessions are independent
1814
+ await session1.sendAndWait({ prompt: "Hello from session 1" });
1815
+ await session2.sendAndWait({ prompt: "Hello from session 2" });
1816
+ ```
1817
+
1818
+ ### Custom Session IDs
1819
+
1820
+ <!-- docs-validate: strict -->
1821
+
1822
+ ```typescript
1823
+ const session = await client.createSession({
1824
+ sessionId: "my-custom-session-id",
1825
+ model: "gpt-5",
1826
+ });
1827
+ ```
1828
+
1829
+ ### File Attachments
1830
+
1831
+ <!-- docs-validate: strict -->
1832
+ <!-- docs-validate: hidden -->
1833
+
1834
+ ```typescript
1835
+ import { approveAll } from "@microsoft/copilot-sdk";
1836
+
1837
+ const session = await client.createSession({ onPermissionRequest: approveAll });
1838
+
1839
+ await session.send({
1840
+ prompt: "Analyze this file",
1841
+ attachments: [
1842
+ {
1843
+ type: "file",
1844
+ path: "/path/to/file.js",
1845
+ displayName: "My File",
1846
+ },
1847
+ ],
1848
+ });
1849
+ ```
1850
+
1851
+ <!-- /docs-validate: hidden -->
1852
+
1853
+ ```typescript
1854
+ await session.send({
1855
+ prompt: "Analyze this file",
1856
+ attachments: [
1857
+ {
1858
+ type: "file",
1859
+ path: "/path/to/file.js",
1860
+ displayName: "My File",
1861
+ },
1862
+ ],
1863
+ });
1864
+ ```
1865
+
1866
+ ### Custom Providers
1867
+
1868
+ 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
+
1870
+ **ProviderConfig:**
1871
+
1872
+ - `type?: "openai" | "azure" | "anthropic"` - Provider type (default: "openai")
1873
+ - `baseUrl: string` - API endpoint URL (required)
1874
+ - `apiKey?: string` - API key (optional for local providers like Ollama)
1875
+ - `bearerToken?: string` - Bearer token for authentication (takes precedence over apiKey)
1876
+ - `wireApi?: "completions" | "responses"` - API format for OpenAI/Azure (default: "completions")
1877
+ - `azure?.apiVersion?: string` - Azure API version; when omitted, the runtime uses the GA versionless `v1` route
1878
+
1879
+ **Example with Ollama:**
1880
+
1881
+ <!-- docs-validate: strict -->
1882
+
1883
+ ```typescript
1884
+ 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
1890
+ },
1891
+ });
1892
+
1893
+ await session.sendAndWait({ prompt: "Hello!" });
1894
+ ```
1895
+
1896
+ **Example with custom OpenAI-compatible API:**
1897
+
1898
+ <!-- docs-validate: strict -->
1899
+
1900
+ ```typescript
1901
+ const session = await client.createSession({
1902
+ model: "gpt-4",
1903
+ provider: {
1904
+ type: "openai",
1905
+ baseUrl: "https://my-api.example.com/v1",
1906
+ apiKey: process.env.MY_API_KEY,
1907
+ },
1908
+ });
1909
+ ```
1910
+
1911
+ **Example with Azure OpenAI:**
1912
+
1913
+ <!-- docs-validate: strict -->
1914
+
1915
+ ```typescript
1916
+ const session = await client.createSession({
1917
+ 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
+ },
1925
+ },
1926
+ });
1927
+ ```
1928
+
1929
+ > **Important notes:**
1930
+ >
1931
+ > - When using a custom provider, the `model` parameter is **required**. The SDK will throw an error if no model is specified.
1932
+ > - For Azure OpenAI endpoints (`*.openai.azure.com`), you **must** use `type: "azure"`, not `type: "openai"`.
1933
+ > - The `baseUrl` should be just the host (e.g., `https://my-resource.openai.azure.com`). Do **not** include `/openai/v1` in the URL - the SDK handles path construction automatically.
1934
+
1935
+ ## Telemetry
1936
+
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:
1938
+
1939
+ <!-- docs-validate: strict -->
1940
+
1941
+ ```typescript
1942
+ import { CopilotClient } from "@microsoft/copilot-sdk";
1943
+
1944
+ const client = new CopilotClient({
1945
+ mode: "coding-agent",
1946
+ telemetry: {
1947
+ otlpEndpoint: "http://localhost:4318",
1948
+ },
1949
+ });
1950
+ ```
1951
+
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.
1953
+
1954
+ **TelemetryConfig options:**
1955
+
1956
+ - `otlpEndpoint?: string` - OTLP HTTP endpoint URL
1957
+ - `otlpProtocol?: "http/json" | "http/protobuf"` - OTLP HTTP protocol for all signals
1958
+ - `filePath?: string` - File path for JSON-lines trace output
1959
+ - `exporterType?: string` - `"otlp-http"` or `"file"`
1960
+ - `sourceName?: string` - Instrumentation scope name
1961
+ - `captureContent?: boolean` - Whether to capture message content
1962
+
1963
+ ### Advanced: Trace Context Propagation
1964
+
1965
+ > **You don't need this for normal telemetry collection.** The `telemetry` config above is sufficient to get full traces from the CLI.
1966
+
1967
+ `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
+
1969
+ If you're already using `@opentelemetry/api` in your app and want this linkage, provide a callback:
1970
+
1971
+ ```typescript
1972
+ import { CopilotClient } from "@microsoft/copilot-sdk";
1973
+ import { propagation, context } from "@opentelemetry/api";
1974
+
1975
+ const client = new CopilotClient({
1976
+ 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;
1982
+ },
1983
+ });
1984
+ ```
1985
+
1986
+ Inbound trace context from the CLI is available on the `ToolInvocation` object passed to tool handlers as `traceparent` and `tracestate` fields. See the [OpenTelemetry guide](../docs/observability/opentelemetry.md) for a full wire-up example.
1987
+
1988
+ ## Permission Handling
1989
+
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.
1991
+
1992
+ 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
+
1994
+ ### Approve All (simplest)
1995
+
1996
+ Use the built-in `approveAll` helper when managed settings are disabled:
1997
+
1998
+ <!-- docs-validate: strict -->
1999
+ <!-- docs-validate: hidden -->
2000
+
2001
+ ```typescript
2002
+ import { approveAll } from "@microsoft/copilot-sdk";
2003
+
2004
+ const session = await client.createSession({
2005
+ model: "gpt-5",
2006
+ onPermissionRequest: approveAll,
2007
+ });
2008
+ ```
2009
+
2010
+ <!-- /docs-validate: hidden -->
2011
+
2012
+ ```typescript
2013
+ import { CopilotClient, approveAll } from "@microsoft/copilot-sdk";
2014
+
2015
+ const session = await client.createSession({
2016
+ model: "gpt-5",
2017
+ onPermissionRequest: approveAll,
2018
+ });
2019
+ ```
2020
+
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.
2022
+
2023
+ ### Custom Permission Handler
2024
+
2025
+ Provide your own function to inspect each request and apply custom logic. Check `managedApprovalRequired` before any automatic approval:
2026
+
2027
+ <!-- docs-validate: strict -->
2028
+
2029
+ ```typescript
2030
+ import type { PermissionRequest, PermissionRequestResult } from "@microsoft/copilot-sdk";
2031
+
2032
+ const session = await client.createSession({
2033
+ 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" };
2061
+ },
2062
+ });
2063
+ ```
2064
+
2065
+ ### Managed network policy for client-owned browsers
2066
+
2067
+ Obtain a reusable `permissionsContext` from
2068
+ `client.rpc.managedSettings.resolve({ selectionId })` for account and device
2069
+ policy, or `session.rpc.managedSettings.get()` for the session's retained policy,
2070
+ including SDK injection and policy-helper rules. Omit `selectionId` for the current
2071
+ account, or device policy only when signed out. Resolution uses the managed-policy
2072
+ cache and can fetch server policy; keep it off latency-critical startup paths.
2073
+ Older runtimes may omit `permissionsContext`. Treat an absent context as unsupported
2074
+ evaluation, not unmanaged policy; do not navigate without a policy decision.
2075
+
2076
+ Call `client.rpc.managedSettings.permissions.evaluate({ context: permissionsContext, operations: [{ kind: "url", url: "https://docs.example.com/guide" }] })`.
2077
+ This is pure, sessionless evaluation: it performs no policy discovery, I/O,
2078
+ prompting, or sandbox changes. Reuse an in-memory context for repeated checks and
2079
+ refresh it when managed policy changes. Retain the runtime-owned `permissions`
2080
+ object verbatim rather than rebuilding it from the flattened settings display.
2081
+
2082
+ The result is `{ results: [{ operation, verdict }], failClosed }`, with one entry per
2083
+ input operation in the same order. `deny` blocks navigation, `ask` requires approval,
2084
+ `allow` approves under managed policy, and `unmanaged` leaves the consumer's normal
2085
+ permission flow in effect. A check never prompts or grants a saved approval.
2086
+ Invalid URLs reject the batch. Unknown policy rejects or returns `failClosed: true`
2087
+ with all URLs denied; do not navigate on an error.
2088
+
2089
+ Check every navigation, redirect, and new-window destination before opening it.
2090
+ These APIs evaluate managed permission rules only: they do not replace browser
2091
+ security checks, user permissions, or sandbox policy. `permissions.limitTo` neither
2092
+ enables the sandbox nor changes `sandbox.userPolicy.network`; configure sandbox
2093
+ network restrictions explicitly.
2094
+
2095
+ ### Policy Helper failures and scoped recheck
2096
+
2097
+ Snapshots may expose `policyHelperFailure` and `policyHelperCapabilities`.
2098
+ Recheck requires session opt-in through `enableManagedSettings: true`.
2099
+ Treat helper text as untrusted plain text, keep `diagnostic` secondary,
2100
+ and sanitize `helpLink` before navigation.
2101
+
2102
+ <!-- docs-validate: strict -->
2103
+ <!-- docs-validate: hidden -->
2104
+
2105
+ ```typescript
2106
+ import type { CopilotSession } from "@microsoft/copilot-sdk";
2107
+
2108
+ declare const session: CopilotSession;
2109
+
2110
+ const snapshot = await session.rpc.managedSettings.get();
2111
+
2112
+ if (snapshot.policyHelperFailure) {
2113
+ console.warn(snapshot.policyHelperFailure.message);
2114
+ }
2115
+
2116
+ if (snapshot.policyHelperCapabilities?.recheck === true) {
2117
+ const refreshed = await session.rpc.managedSettings.recheckPolicyHelper();
2118
+ // Only a current capable snapshot without policyHelperFailure establishes recovery.
2119
+ console.log(refreshed.policyHelperFailure ?? "Policy Helper recovered");
2120
+ }
2121
+ ```
2122
+
2123
+ <!-- /docs-validate: hidden -->
2124
+
2125
+ ```typescript
2126
+ const snapshot = await session.rpc.managedSettings.get();
2127
+
2128
+ if (snapshot.policyHelperFailure) {
2129
+ console.warn(snapshot.policyHelperFailure.message);
2130
+ }
2131
+
2132
+ if (snapshot.policyHelperCapabilities?.recheck === true) {
2133
+ const refreshed = await session.rpc.managedSettings.recheckPolicyHelper();
2134
+ // Only a current capable snapshot without policyHelperFailure establishes recovery.
2135
+ console.log(refreshed.policyHelperFailure ?? "Policy Helper recovered");
2136
+ }
2137
+ ```
2138
+
2139
+ Older runtimes omit `policyHelperCapabilities`. Do not infer support or recovery
2140
+ only because `policyHelperFailure` is absent. Only applicable `session.create` and
2141
+ `session.resume` failures attach it to `error.data.policyHelperFailure`, retaining
2142
+ the primary code/message. Activation callers read
2143
+ `managedSettings.resolve(...).resolved.policyHelperFailure` instead.
2144
+
2145
+ ### Permission Result Kinds
2146
+
2147
+ The handler must return one of the `PermissionDecision` shapes (or `{ kind: "no-result" }`). Approval scopes are present-tense — they describe the decision to apply, not the outcome reported back on session events:
2148
+
2149
+ | Kind | Meaning | Extra fields |
2150
+ | ------------------------ | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
2151
+ | `"approve-once"` | Allow this single request | — |
2152
+ | `"approve-for-session"` | Allow this request and remember the approval for the rest of the session | `approval?` (rule to remember), `domain?` (for URL approvals) |
2153
+ | `"approve-for-location"` | Allow this request and persist the approval for this project location (git root or cwd) | `approval` (rule to persist), `locationKey` (location to persist under) |
2154
+ | `"approve-permanently"` | Allow this request and persist the approval across sessions (currently used for URL domains) | `domain` (URL domain to approve) |
2155
+ | `"reject"` | Deny the request | `feedback?` (optional string surfaced to the agent) |
2156
+ | `"user-not-available"` | Deny the request because no user is available to confirm it | — |
2157
+ | `"no-result"` | Suppress this SDK client's response so another connected client can answer the pending request | — |
2158
+
2159
+ ### Resuming Sessions
2160
+
2161
+ You may pass `onPermissionRequest` when resuming a session too:
2162
+
2163
+ <!-- docs-validate: strict -->
2164
+ <!-- docs-validate: hidden -->
2165
+
2166
+ ```typescript
2167
+ import { approveAll } from "@microsoft/copilot-sdk";
2168
+
2169
+ const session = await client.resumeSession("session-id", {
2170
+ onPermissionRequest: approveAll,
2171
+ });
2172
+ ```
2173
+
2174
+ <!-- /docs-validate: hidden -->
2175
+
2176
+ ```typescript
2177
+ const session = await client.resumeSession("session-id", {
2178
+ onPermissionRequest: approveAll,
2179
+ });
2180
+ ```
2181
+
2182
+ ### Per-Tool Skip Permission
2183
+
2184
+ To let a specific custom tool bypass the permission prompt entirely, set `skipPermission: true` on the tool definition. See [Skipping Permission Prompts](#skipping-permission-prompts) under Tools.
2185
+
2186
+ ## User Input Requests
2187
+
2188
+ Enable the legacy question-and-answer `ask_user` tool by providing an `onUserInputRequest` handler:
2189
+
2190
+ <!-- docs-validate: strict -->
2191
+
2192
+ ```typescript
2193
+ const session = await client.createSession({
2194
+ 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
+ };
2211
+ },
2212
+ });
2213
+ ```
2214
+
2215
+ ## Elicitation Requests
2216
+
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.
2218
+
2219
+ <!-- docs-validate: strict -->
2220
+
2221
+ ```typescript
2222
+ import { approveAll } from "@microsoft/copilot-sdk";
2223
+
2224
+ const session = await client.createSession({
2225
+ 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
+ };
2242
+ },
2243
+ });
2244
+
2245
+ // The session now reports elicitation capability
2246
+ console.log(session.capabilities.ui?.elicitation); // true
2247
+ ```
2248
+
2249
+ Set `askUserVariant: "elicitation"` to expose the structured form as the model's
2250
+ `ask_user` tool. Omit it to retain the legacy SDK behavior.
2251
+
2252
+ When `onElicitationRequest` is provided, the SDK sends `requestElicitation: true` during session create/resume, which enables `session.capabilities.ui.elicitation` on the session.
2253
+
2254
+ In multi-client scenarios:
2255
+
2256
+ - If no connected client was previously providing an elicitation capability, but a new client joins that can, all clients will receive a `capabilities.changed` event to notify them that elicitation is now possible. The SDK automatically updates `session.capabilities` when these events arrive.
2257
+ - Similarly, if the last elicitation provider disconnects, all clients receive a `capabilities.changed` event indicating elicitation is no longer available.
2258
+ - The server fans out elicitation requests to **all** connected clients that registered a handler — the first response wins.
2259
+
2260
+ ## Session Hooks
2261
+
2262
+ Hook into session lifecycle events by providing handlers in the `hooks` configuration:
2263
+
2264
+ <!-- docs-validate: strict -->
2265
+ <!-- docs-validate: hidden -->
2266
+
2267
+ ```typescript
2268
+ declare function needsMoreWork(): boolean;
2269
+
2270
+ const session = await client.createSession({
2271
+ model: "gpt-5",
2272
+ 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
+ },
2292
+
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
+ },
2302
+
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
+ },
2310
+
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
+ },
2318
+
2319
+ // Called when session ends
2320
+ onSessionEnd: async (input, invocation) => {
2321
+ console.log(`Session ended: ${input.reason}`);
2322
+ },
2323
+
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
+ },
2331
+
2332
+ // Called when the top-level agent naturally stops
2333
+ onAgentStop: async (input, invocation) => {
2334
+ if (!input.stopHookActive && needsMoreWork()) {
2335
+ return {
2336
+ decision: "block",
2337
+ reason: "Run the final validation and fix any failures.",
2338
+ };
2339
+ }
2340
+ },
2341
+
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
+ },
2347
+
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}` };
2354
+ },
2355
+ },
2356
+ });
2357
+ ```
2358
+
2359
+ <!-- /docs-validate: hidden -->
2360
+
2361
+ ```typescript
2362
+ const session = await client.createSession({
2363
+ model: "gpt-5",
2364
+ 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
+ },
2384
+
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
+ },
2394
+
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
+ },
2402
+
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
+ },
2410
+
2411
+ // Called when session ends
2412
+ onSessionEnd: async (input, invocation) => {
2413
+ console.log(`Session ended: ${input.reason}`);
2414
+ },
2415
+
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
+ },
2423
+
2424
+ // Called when the top-level agent naturally stops
2425
+ onAgentStop: async (input, invocation) => {
2426
+ if (!input.stopHookActive && needsMoreWork()) {
2427
+ return {
2428
+ decision: "block",
2429
+ reason: "Run the final validation and fix any failures.",
2430
+ };
2431
+ }
2432
+ },
2433
+
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
+ },
2439
+
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}` };
2446
+ },
2447
+ },
2448
+ });
2449
+ ```
2450
+
2451
+ **Available hooks:**
2452
+
2453
+ - `onPreToolUse` - Intercept tool calls before execution. Can allow/deny or modify arguments.
2454
+ - `onPostToolUse` - Process tool results after **successful** execution. Can modify results or add context.
2455
+ - `onPostToolUseFailure` - Observe and append hidden guidance to the model after tool executions whose result was `"failure"`. Register this in addition to `onPostToolUse` to see failed tool calls.
2456
+ - `onUserPromptSubmitted` - Intercept user prompts. Can modify the prompt before processing, or return `{ decision: "block", reason }` to refuse it: no model turn runs, no user message is recorded, and the session emits an ephemeral `session.warning` (`warningType: "policy_blocked"`) carrying the reason.
2457
+ - `onSessionStart` - Run logic when a session starts or resumes.
2458
+ - `onSessionEnd` - Cleanup or logging when session ends.
2459
+ - `onErrorOccurred` - Handle errors with retry/skip/abort strategies.
2460
+ - `onAgentStop` - Observe natural top-level agent completion. Return `{ decision: "block", reason }` to request another turn; use `stopHookActive` to avoid repeated blocks.
2461
+ - `onSubagentStart` - Observe a sub-agent before its first turn and prepend `additionalContext` to the child's prompt.
2462
+ - `onSubagentStop` - Observe a sub-agent's final response. Return `{ decision: "block", reason }` to request another child turn, or `{ modifiedResponse }` to replace the response reported to the parent.
2463
+
2464
+ ## Error Handling
2465
+
2466
+ <!-- docs-validate: strict -->
2467
+
2468
+ ```typescript
2469
+ try {
2470
+ const session = await client.createSession({});
2471
+ await session.send({ prompt: "Hello" });
2472
+ } catch (error) {
2473
+ console.error("Error:", error instanceof Error ? error.message : error);
2474
+ }
2475
+ ```
2476
+
2477
+ ## Development
2478
+
2479
+ From the repository root:
2480
+
2481
+ ```bash
2482
+ cd test/harness
2483
+ npm ci
2484
+ ```
2485
+
2486
+ ```bash
2487
+ cd nodejs
2488
+ npm ci
2489
+ npm test
2490
+ ```
2491
+
2492
+ ### Internal feature-flag example
2493
+
2494
+ [`examples/internal-feature-flags.ts`](examples/internal-feature-flags.ts) uses
2495
+ the generated internal RPC factory against a real runtime over stdio.
2496
+ It lists the catalog and shows environment, settings, and explicit-override
2497
+ precedence. It also checks that static resolution does not apply `COPILOT_EXP_*`
2498
+ experiment assignments. It creates no session and sends no model request.
2499
+
2500
+ After you prepare matching runtime artifacts, run this from the runtime repository root:
2501
+
2502
+ ```bash
2503
+ COPILOT_RUNTIME_PROVIDER_LIB="$PWD/bazel-bin/src/native/runtime/runtime.node" \
2504
+ src/sdk/nodejs/node_modules/.bin/tsx \
2505
+ src/sdk/nodejs/examples/internal-feature-flags.ts \
2506
+ "$PWD/bazel-bin/src/runtime-bin/copilot-runtime"
2507
+ ```
2508
+
2509
+ The JSON output includes `staticResolution` values of `false`, `true`, `false`,
2510
+ and `true`, in that order. These methods are internal, not public SDK APIs.
2511
+
2512
+ ## License
2513
+
2514
+ MIT