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